There is no implicit type conversion in Swift for safety reasons. You must convert deg
to a Float
. Literals don't have an implicit type and can act as number of different types, but by initiating the division first, the type is chosen before it can be decided by the type of deg
. Therefore, you must convert the result of M_PI/180.0
as well:
func degToRad(deg: Int) -> Float {
return Float(deg) * Float(M_PI / 180.0)
}
And to potentially entice you with the language a bit more. Here is a handy enum for AngularMeasure:
enum AngularMeasure {
case Degrees(CGFloat)
case Radians(CGFloat)
var degrees: CGFloat {
switch (self) {
case let .Degrees(value):
return value
case let .Radians(value):
return value * CGFloat(180.0 / M_PI)
}
}
var radians: CGFloat {
switch (self) {
case let .Degrees(value):
return value * CGFloat(M_PI / 180.0)
case let .Radians(value):
return value
}
}
}
var measure : AngularMeasure = .Degrees(180)
println(measure.radians) // 3.14159274101257
Edit:
With your update, you are trying to call an instance method as a class method. You need to define your method as a class method:
class func degToRad(deg:Double) -> CGFloat {
return CGFloat(deg*(M_PI/180.0))
}
Again, this is a terrible compiler error.