Reputation: 39081
Im having some very frustrating issues with this function:
func degToRad(deg:Int) -> Float {
return deg*(M_PI/180.0)
}
At the return
line I get an error message: 'Int' is not convertible to 'UInt8'
This is really driving me nuts. This would work in Obj-C
. Im really starting to question Swift
as a language...
UPDATE
I updated my function to this:
func degToRad(deg:Double) -> CGFloat {
return CGFloat(deg*(M_PI/180.0))
}
But when I try to use it like this:
CGAffineTransformMakeRotation(CFunctions.degToRad(90))
I get the same error except Double -> CGFloat not convertible
Upvotes: 0
Views: 9746
Reputation: 94733
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.
Upvotes: 10
Reputation: 535345
The thing to understand is that there is no implicit casting of numeric types to one another. Literals are cast because they have no actual type at the outset, but variables are not.
The only "natural" types are Int and Double, and Float is neither of those. Thus, to return a Float you need to cast the whole result to a Float:
func degToRad(deg:Int) -> Float {
return Float(deg*(M_PI/180.0))
}
But even this will not be enough, because deg
comes in as an Int, while M_PI
and 180.0
are Double, so it must be cast too:
func degToRad(deg:Int) -> Float {
return Float(Double(deg)*(M_PI/180.0))
}
Upvotes: 4
Reputation: 100632
The error message looks like a current deficiency in the compiler but the mistake is not explicitly casting deg
to Float
. There is no implicit type conversion in Swift (teleologically because the bugs it sometimes produces are not considered worth the reduction in syntax).
Upvotes: 1