將一種數字型別轉換為另一種

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