Swift 元組 (Tuples)

元組 (Tuple) 是一個非常實用的輕量級資料結構,它允許你將多個值結合成一個單一的複合值。這些值可以是不同型別

定義元組

你可以用小括號 () 將多個值包起來定義一個元組:

let http404Error = (404, "Not Found")
// http404Error 的型別是 (Int, String)

在這個例子中,http404Error 描述了一個 HTTP 狀態碼,它包含了一個數字 (404) 和一個描述字串 ("Not Found")。

存取元組內容

1. 使用索引 (Index)

你可以像存取陣列一樣,用索引來取得元組內的值 (索引從 0 開始):

print("The status code is \(http404Error.0)")
print("The status message is \(http404Error.1)")

2. 給元素命名

定義元組時,你也可以給每個元素取個名字:

let http200Status = (statusCode: 200, description: "OK")

這樣你就可以用名字來存取值,可讀性更高:

print("The status code is \(http200Status.statusCode)")
print("The status message is \(http200Status.description)")

3. 分解元組 (Decomposition)

你也可以將元組內的內容一次拆解並賦值給多個變數:

let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
print("The status message is \(statusMessage)")

如果你只需要其中某個值,可以用底線 _ 忽略其他部分:

let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")

使用時機

元組非常適合作為函式的回傳值。當你需要從一個函式回傳多個相關的值時 (例如一個座標 (x, y),或者一個成功狀態與錯誤訊息 (success, message)),元組是最佳選擇,你不需要為此特地去定義一個新的結構 (Struct) 或類別 (Class)。

元組適合用於暫時性的輕量資料群組。如果你的資料結構較複雜或需要長期存在,建議定義一個 StructClass