Search code examples
castingswiftcgfloat

Casting CGFloat to Float in Swift


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?


Solution

  • You can use the Float() initializer:

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