Swift 元組Tuple

Swift 增加了 Objective-C 中沒有的高階數據類型元組(Tuple)。

元組可以讓你創建或者傳遞一組數據,比如作爲函數的返回值時,你可以用一個元組可以返回多個值。

元組 

元組(tuples)把多個值組合成一個複合值。元組內的值可以是任意類型,並不要求是相同類型。

下面這個例子中,(404, "Not Found") 是一個描述 HTTP 狀態碼(HTTP status code)的元組。HTTP 狀態碼是當你請求網頁的時候 web 服務器返回的一個特殊值。如果你請求的網頁不存在就會返回一個 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) 或者 (String, Bool) 或者其他任何你想要的組合的元組。

你可以將一個元組的內容分解(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”

作爲函數返回值時,元組非常有用。一個用來獲取網頁的函數可能會返回一個 (Int, String) 元組來描述是否獲取成功。和只能返回一個類型的值比較起來,一個包含兩個不同類型值的元組可以讓函數的返回信息更有用。

多重返回值函數 

你可以用元組(tuple)類型讓多個值作爲一個複合值從函數中返回。

下例中定義了一個名爲 minMax(array:) 的函數,作用是在一個 Int 類型的數組中找出最小值與最大值。

func minMax(array: [Int]) -> (min: Int, max: Int) {
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1..<array.count] {
        if value < currentMin {
            currentMin = value
        } else if value > currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}

minMax(array:) 函數返回一個包含兩個 Int 值的元組,這些值被標記爲 min 和 max ,以便查詢函數的返回值時可以通過名字訪問它們。

在 minMax(array:) 的函數體中,在開始的時候設置兩個工作變量 currentMin 和 currentMax 的值爲數組中的第一個數。然後函數會遍歷數組中剩餘的值並檢查該值是否比 currentMin 和 currentMax更小或更大。最後數組中的最小值與最大值作爲一個包含兩個 Int 值的元組返回。

因爲元組的成員值已被命名,因此可以通過 . 語法來檢索找到的最小值與最大值:

let bounds = minMax(array: [8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")
// 打印“min is -6 and max is 109”

需要注意的是,元組的成員不需要在元組從函數中返回時命名,因爲它們的名字已經在函數返回類型中指定了。

 

注意

當遇到一些相關值的簡單分組時,元組是很有用的。元組不適合用來創建複雜的數據結構。如果你的數據結構比較複雜,不要使用元組,用類或結構體去建模。欲獲得更多信息。

 

Swift中文手冊:https://www.runoob.com/manual/gitbook/swift5/source/_book/chapter2/01_The_Basics.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章