Casting CGFloat to Float in Swift

Andrew Ebling

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?

Erik

You can use the Float() initializer:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related