元組(tuples)把多個(gè)值組合成一個(gè)復(fù)合值槐秧。元組內(nèi)的值可以是任意類型,并不要求是相同類型掖蛤。
例如:
let http404Error = (404, "Not Found");
將元組的內(nèi)容分解(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"
如果只需要一部分元組值杀捻,分解的時(shí)候可以把要忽略的部分用下劃線(_)標(biāo)記:
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// 輸出 "The status code is 404"
通過下標(biāo)來(lái)訪問元組中的單個(gè)元素,下標(biāo)從零開始:
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"
定義元組的時(shí)候給單個(gè)元素命名:
let http200Status = (statusCode: 200, description: "OK")
給元組中的元素命名后蚓庭,通過名字來(lái)獲取這些元素的值:
print("The status code is \(http200Status.statusCode)")
// 輸出 "The status code is 200"
print("The status message is \(http200Status.description)")
// 輸出 "The status message is OK"
來(lái)自:http://www.piggybear.net/?p=715