數字型別和文字
Swift 的內建數字型別是:
- 字大小(依賴於體系結構)簽名的 Int 和 unsigned UInt 。
- 固定大小的有符號整數 Int8 , Int16 , Int32 , Int64 和無符號整數 UInt8 , UInt16 , UInt32 , UInt64 。
- 浮點型別 Float32 / Float , Float64 / Double 和 Float80 (僅限 x86)。
字面
從上下文推斷出數字文字的型別:
let x = 42 // x is Int by default
let y = 42.0 // y is Double by default
let z: UInt = 42 // z is UInt
let w: Float = -1 // w is Float
let q = 100 as Int8 // q is Int8
下劃線(_
)可用於分隔數字文字中的數字。前導零被忽略。
可以使用有效數和指數部分( 對於十進位制; 對於十六進位制) 指定浮點文字。 «significand» e «exponent»
0x «significand» p «exponent»
整數文字語法
let decimal = 10 // ten
let decimal = -1000 // negative one thousand
let decimal = -1_000 // equivalent to -1000
let decimal = 42_42_42 // equivalent to 424242
let decimal = 0755 // equivalent to 755, NOT 493 as in some other languages
let decimal = 0123456789
let hexadecimal = 0x10 // equivalent to 16
let hexadecimal = 0x7FFFFFFF
let hexadecimal = 0xBadFace
let hexadecimal = 0x0123_4567_89ab_cdef
let octal = 0o10 // equivalent to 8
let octal = 0o755 // equivalent to 493
let octal = -0o0123_4567
let binary = -0b101010 // equivalent to -42
let binary = 0b111_101_101 // equivalent to 0o755
let binary = 0b1011_1010_1101 // equivalent to 0xB_A_D
浮點字面語法
let decimal = 0.0
let decimal = -42.0123456789
let decimal = 1_000.234_567_89
let decimal = 4.567e5 // equivalent to 4.567×10⁵, or 456_700.0
let decimal = -2E-4 // equivalent to -2×10⁻⁴, or -0.0002
let decimal = 1e+0 // equivalent to 1×10⁰, or 1.0
let hexadecimal = 0x1p0 // equivalent to 1×2⁰, or 1.0
let hexadecimal = 0x1p-2 // equivalent to 1×2⁻², or 0.25
let hexadecimal = 0xFEEDp+3 // equivalent to 65261×2³, or 522088.0
let hexadecimal = 0x1234.5P4 // equivalent to 0x12345, or 74565.0
let hexadecimal = 0x123.45P8 // equivalent to 0x12345, or 74565.0
let hexadecimal = 0x12.345P12 // equivalent to 0x12345, or 74565.0
let hexadecimal = 0x1.2345P16 // equivalent to 0x12345, or 74565.0
let hexadecimal = 0x0.12345P20 // equivalent to 0x12345, or 74565.0