元組將多個值分組為單個復(fù)合值。 元組中的值可以是任何類型,并且不必具有彼此相同的類型。
在此示例中,(404,“NotFound”)是描述HTTP狀態(tài)代碼的元組。 HTTP狀態(tài)代碼是Web服務(wù)器在您請求網(wǎng)頁時返回的特殊值。 如果您請求的網(wǎng)頁不存在,則會返回404未找到的狀態(tài)代碼。
let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
您可以從任何類型的排列創(chuàng)建元組,并且它們可以包含任意多種不同類型。 沒有什么能阻止你有一個類型(Int,Int,Int)或(String,Bool)的元組,或者你需要的任何其他排列。
您可以將表的內(nèi)容分解為單獨的常量或變量,然后您可以像平常一樣訪問:
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// Prints "The status code is 404"
print("The status message is \(statusMessage)")
// Prints "The status message is Not Found"
如果只需要一些元組值,在分解元組時,使用下劃線(_)忽略元組的一部分:
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// Prints "The status code is 404"
或者,使用從零開始的索引號訪問元組中的各個元素值:
print("The status code is \(http404Error.0)")
// Prints "The status code is 404"
print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"
當(dāng)定義元組時,您可以在元組中給每個元素命名:
let http200Status = (statusCode: 200, description: "OK")
如果給元組中的元素命名,則可以使用元素名稱訪問這些元素的值:
print("The status code is \(http200Status.statusCode)")
// Prints "The status code is 200"
print("The status message is \(http200Status.description)")
// Prints "The status message is OK"
元組作為函數(shù)的返回值特別有用。 嘗試檢索網(wǎng)頁的函數(shù)可能返回(Int,String)元組類型,以描述頁面檢索的成功或失敗。 通過返回具有兩個不同值的元組,每個值具有不同的類型,該函數(shù)提供關(guān)于其結(jié)果的更有用的信息,而不是返回單個類型的單個值。