CGFloat Casting for Swift Swim

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

 let myFloat : Float = myRect.origin.x 

but this leads to a compiler error: "NSNumber" does not apply to the subtype "Float"

So, if I explicitly use it as follows:

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

but this in turn leads to a compiler error: "Cannot convert the type of the expression" Float "to" Float "

What is the correct way to do this and satisfy the compiler?

+75
casting swift cgfloat
Jun 10 '14 at
source share
3 answers

You can use the initializer Float() :

 let cgFloat: CGFloat = 3.14159 let someFloat = Float(cgFloat) 
+138
Jun 10 '14 at
source share

If you're as lazy as I am, in Extensions.swift, define the following:

 extension Int { var f: CGFloat { return CGFloat(self) } } extension Float { var f: CGFloat { return CGFloat(self) } } extension Double { var f: CGFloat { return CGFloat(self) } } extension CGFloat { var swf: Float { return Float(self) } } 

Then you can do:

 var someCGFloatFromFloat = 1.3.f var someCGFloatFromInt = 2.f var someFloatFromCGFloat = someCGFloatFromFloat.swf 
+24
Nov 09 '14 at 16:47
source share

Usually the best solution is to save the type and use CGFloat , even in Swift. This is because CGFloat has different sizes on 32-bit and 64-bit machines.

The as keyword can only be used for a dynamic cast (for subclasses), for example

 class A { } class B : A { } var a: A = B() var b: B = a as B 

However, Double , Int , Float , etc. are not subclasses of each other, so for "cast" you need to create a new instance, for example

 var d: Double = 2.0 var f: Float = Float(d) //this is an initialiser call, not a cast var i: Int = Int(d) //this is an initialiser call, not a cast 
+13
Jun 10 '14 at 18:04
source share



All Articles