元組(tuples)把多個值組合成一個複合值。元組內的值可以是任意型別,並不要求是相同型別。
例如:
let http404Error = (404, "Not Found");
將元組的內容分解(decompose)
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// 輸出 "The status code is 404"
print("The status message is \(statusMessage)")
// 輸出 "The status message is Not Found"
複製程式碼
如果只需要一部分元組值,分解的時候可以把要忽略的部分用下劃線(_)標記:
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// 輸出 "The status code is 404"
複製程式碼
通過下標來訪問元組中的單個元素,下標從零開始:
print("The status code is \(http404Error.0)")
// 輸出 "The status code is 404"
print("The status message is \(http404Error.1)")
// 輸出 "The status message is Not Found"
複製程式碼
定義元組的時候給單個元素命名:
let http200Status = (statusCode: 200, description: "OK")
複製程式碼
給元組中的元素命名後,通過名字來獲取這些元素的值:
print("The status code is \(http200Status.statusCode)")
// 輸出 "The status code is 200"
print("The status message is \(http200Status.description)")
// 輸出 "The status message is OK"
複製程式碼
來自:http://www.piggybear.net/?p=715