Swift Language Converti un tipo numerico in un altro


Esempio

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

Gli inizializzatori integer generano un errore di runtime se il valore trabocca o underflow:

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

Conversione da virgola mobile a valori interi arrotonda i valori verso zero :

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

La conversione da intero a float potrebbe essere una perdita :

Int(Float(1_000_000_000_000_000_000))  // 999999984306749440