1.數字字面量
整形字面量可以被寫成如下的形式:
- 十進制(decimal)數字,不需要加前綴
- 二進制(binary)數字,需要加 0b 作為前綴
- 八進制(octal)數字,需要加 0o 作為前綴
- 十六進制(hexadecimal)數字,需要加 0x 作為前綴
示例:
let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
2.指數表達式
十進制數字表示方式:
//e搭配后面的數子,表示10的多少次方
1.25e2 代表 1.25 x 10^2 或者 125.0
1.25e-2 代表 1.25 x 10^-2 或者 0.0125
十六進制數字表示方式:
//0x 表示 16進制,F 為16進制的數字15,p搭配后面的數字,表示2的多少次方
0xFp2 代表 15 x 2^2 或者 60.0
0xFp-2 代表 15 x 2^-2 或者 3.75
看一下幾個例子:
let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0
//他們的值都是 12.1875
為了增加大數字的可讀性,swift新添了一樣數字表示格式
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
3.bool類型做條件判斷
在 if 條件語句中我們都知道,凡是能夠表達 真(非0) 或者 假(0) 的表達式都可以作為條件進行判斷處理,但是在 Swift 中做了一些改進,因為 Swift 是類型安全的,在使用條件語句時,會阻止 非 Boolean 值的表達式作為邏輯語句,看一下下面的例子:
//錯誤的條件語句
let i = 1
if i {
// this example will not compile, and will report an error
}
//正確的條件語句
let j = 1
if j == 1 {
// this example will compile successfully
}
4.元組
元組:包含多個值到一個復合值里,即值的集合(有點像數組,但跟數組還是有很大區別)。
例如:(404, "Not Found")
就是一個元組,是我們常用來描述HTTP狀態嗎的信息,404 Not Found
常被用來表示網頁不存在。
let http404Error = (404, "Not Found")
// http404Error 類型是 (Int, String), 等價于 (404, "Not Found")
(404, "Not Found")
作為一個元組,集合了 Int
和 String
兩個分離的值作為HTTP
的狀態碼,元組類型則是:(Int, String)
,當然我們可以創建一組任意類型的值,例如:(Int, Int, Int)
or (String, Bool)
我們也可以把元組的內容分解為 常量(constants)或者 變量(variables),如下:
let http404error = (404,"Not Found")
let (statusCode,statusMessage) = http404error
print("status code is \(statusCode)")
print("status message is \(statusMessage)")
如果我們只需要一部分元組的值,而想要忽略掉另外一部分值,可以使用下劃線_
進行忽略,分解如下:
let http404error = (404,"Not Found")
let (statusCode,_) = http404error
print("status code is \(statusCode)")
對于一個已經初始化的元組,我們可以使用下表訪問的方式,進行訪問元組內部的值,如下:
let http404error = (404,"Not Found")
print("status code is \(http404error.0)")
print("status message is \(http404error.1)")
在初始化元組時也可以給每個元組的值命名,這樣使元組更易讀,如下:
let http404error = (statusCode:404,description:"Not Found")
print("status code is \(http404error.statusCode)")
print("status message is \(http404error.description)")
元組作為函數的返回值是比較有用的,返回的一個值能夠具體的描述處理結果的信息,有利于我們對邏輯的處理,后續會談到。