Tuples

Tuples,在近代的程式語言中才演化出來的東西,它的概念在 Python、Scala 等語言中都常常會看到,Swift 導加入了 Tuples,也有 Pattern Matching 的概念,讓寫程式更加暢行無阻呀!

Tuples 就像是一個集合:

(3.79, 3.99, 4.19)       //(Double, Double, Double)
(404, "Not found")       //(Int, String)
(2, "banana", 0.72)       //(Int, String, Double)

Decomposing a Tuple (解碼一個 tuple)

在之前的範例中,我們有一個 function 會回傳兩個值。在 Swift 中可以用 tuple 去接收這個 function 的回傳值。這也就利用到 Pattern Matching 的方法,Swift 會自動把 function 的「回傳值」 matching 到 (statusCode, message)

func refreshWebPage() -> (Int, String) {
   // ...try to refresh...
   return (200, "Success")
}

let (statusCode, message) = refreshWebPage()

println("Receive \(statusCode): \(message)")

輸出結果為:

Received 200: Success

此外我們也可以指定 tuple 裡面元素(element)的型態,例如:

func refreshWebPage() -> (Int, String) {
   // ...try to refresh...
   return (200, "Success")
}

let (statusCode: Int, message: String) = refreshWebPage()

println("Received \(statusCode): \(message)")

輸出結果為:

Received 200: Success

Tuple Decomposition for Enumeration

Tuplefor 迴圈中也會用到,例如:

let numberOfLegs = ["ant": 6, "snake": 0, "cheetah": 4]

for (animalName, legCount) in numberOfLegs {
   println("\(animalName)s have \(legCount) legs")
}

輸出結果為:

ants have 6 legs
snakes have 0 legs
cheetahs have 4 legs

Named Values in a Tuple

tuple 中,可以對其元素宣告變數名稱,例如:

func refreshWebPage() -> (code: Int, message: String) {
   // ...try to refresh...
   return (200, "Success")
}

let status = refreshWebPage()

println("Received \(status.code): \(status.message)")

輸出結果為:

Received 200: Success

下一篇: Closures