Casting CGFloat to Float in Swift

Andrew Ebling picture Andrew Ebling · Jun 10, 2014 · Viewed 86.9k times · Source

I need to store a value as a Float, but the source data is a CGFloat:

let myFloat : Float = myRect.origin.x

but this results in the compiler error: 'NSNumber' is not of subtype 'Float'

So if I explicitly cast it like this:

let myFloat : Float = myRect.origin.x as Float

but this in turn results in the compiler error: 'Cannot convert the expression's type 'Float' to 'Float''

What's the correct way to do this and satisfy the compiler please?

Answer

Erik picture Erik · Jun 10, 2014

You can use the Float() initializer:

let cgFloat: CGFloat = 3.14159
let someFloat = Float(cgFloat)