1. 程式人生 > >Swift基礎語法簡介(二)——元組

Swift基礎語法簡介(二)——元組

  元組把多個值合併成單一的複合型的值。元組內的值可以是任何型別,而且可以不必是同一型別。

  元組是關係資料庫中的基本概念,關係是一張表,表中的每行(即資料庫中的每條記錄)就是一個元組,每列就是一個屬性。在二維表裡,元組也成為行。

  例如,(404, “Not Found”)是一個描述了HTTP狀態程式碼的元組。HTTP狀態程式碼是當你請求網頁的時候web伺服器返回的一個特殊值。當你請求不存在的網頁時,就會返回404 Not Found。

let http404Error =(404, "Not

Found")  // http404Erroris of type (Int, String)

(404, "Not Found")元組把一個Int和一個String組合起來表示HTTP狀態程式碼的兩種不同的值:數字和人類可讀的描述。它可以被描述為“一個型別為(Int, String)”的元組

  再比如let student = ("001", "Wenxin", "11",

"女", "六一班")可以代表某個學生的元組(學號, 姓名, 年齡, 性別, 班級)。

  你也可以將一個元組的內容分解成單獨的常量或變數,這樣你就可以正常的使用它們了:

let (statusCode, statusMessage) = http404Error

print("The status code is \(statusCode)")

// prints "The status code is404"

print("The status message is \(statusMessage)")

// prints "The status message is NotFound"

  當你分解元組的時候,如果只需要使用其中的一部分資料,不需要的資料可以用下劃線(_)代替:

let http404Error = (404, "NotFound")

let (justTheStatusCode, _) = http404Error

print("The status code is \(justTheStatusCode)")

// prints "The status code is404"

另一種方法就是利用從零開始的索引數字訪問元組中的單獨元素:

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

// prints "The status code is404"

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

// prints "The status message is NotFound"

你可以在定義元組的時候給其中的單個元素命名:

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

在命名之後,你就可以通過訪問名字來獲取元素的值了:

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

// prints "The status code is200"

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

// prints "The status message isOK"

作為函式返回值時,元組非常有用。

例如:定義了一個叫做minMax(array:)的函式,它可以找到型別為Int的陣列中最大數字和最小數字。

func minMax(array: [Int]) -> (min: Int, max:Int) {

var currentMin = array[0]

var currentMax = array[0]

for value in array[1..

ifvalue < currentMin {

currentMin= value

}else if value > currentMax {

currentMax= value

}

}

return (currentMin,currentMax)

}

函式minMax(array:)返回了一個包含兩個Int值的元組。這兩個值被 min和max 標記,這樣當查詢函式返回值的時候就可以通過名字訪問了。

小問題:理論上用字典或者是建一個Model也能實現函式返回多值的問題,那元組與這兩種方式相比有什麼優勢?歡迎評論區留言!!!