Search code examples
iosswiftintuint8t

Int not convertible to UInt8?


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


Solution

  • 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.