将一种数字类型转换为另一种
func doSomething1(value: Double) { /* ... */ }
func doSomething2(value: UInt) { /* ... */ }
let x = 42 // x is an Int
doSomething1(Double(x)) // convert x to a Double
doSomething2(UInt(x)) // convert x to a UInt
如果值溢出或下溢,整数初始值设定项会产生运行时错误 :
Int8(-129.0) // fatal error: floating point value cannot be converted to Int8 because it is less than Int8.min
Int8(-129) // crash: EXC_BAD_INSTRUCTION / SIGILL
Int8(-128) // ok
Int8(-2) // ok
Int8(17) // ok
Int8(127) // ok
Int8(128) // crash: EXC_BAD_INSTRUCTION / SIGILL
Int8(128.0) // fatal error: floating point value cannot be converted to Int8 because it is greater than Int8.max
浮点到整数转换将值舍入为零 :
Int(-2.2) // -2
Int(-1.9) // -1
Int(-0.1) // 0
Int(1.0) // 1
Int(1.2) // 1
Int(1.9) // 1
Int(2.0) // 2
整数到浮点转换可能是有损的 :
Int(Float(1_000_000_000_000_000_000)) // 999999984306749440