CGFloat 快速漂浮铸造

我需要将一个值存储为 Float,但是源数据是 CGFloat:

let myFloat : Float = myRect.origin.x

但这会导致编译器错误: ‘ NSNumber’不属于‘ Float’子类型

所以如果我这样明确地表示:

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

但这反过来又会导致编译器错误: ‘无法将表达式的类型‘ Float’转换为‘ Float’’

什么是正确的方法来做到这一点,并满足编译器请?

90873 次浏览

You can use the Float() initializer:

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

Usually, the best solution is to keep the type and use CGFloat, even in Swift. That's because CGFloat has different size on 32bit and 64bit machines.

Keyword as can be used only for dynamic casting (for subclasses), e.g.

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, therefore to "cast" you have to create a new instance, e.g.

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

If you are as lazy as I am, in an 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