什麼是元組

元組將多個值分組為單個複合值。元組中的值可以是任何型別,並且不必彼此具有相同的型別。

通過對任意數量的值進行分組來建立元組:

let tuple = ("one", 2, "three")

// Values are read using index numbers starting at zero
print(tuple.0) // one
print(tuple.1) // 2
print(tuple.2) // three

在定義元組時,也可以命名單個值:

let namedTuple = (first: 1, middle: "dos", last: 3)

// Values can be read with the named property
print(namedTuple.first)  // 1
print(namedTuple.middle) // dos

// And still with the index number
print(namedTuple.2)      // 3

它們也可以在用作變數時命名,甚至可以在其中包含可選值:

var numbers: (optionalFirst: Int?, middle: String, last: Int)?

//Later On
numbers = (nil, "dos", 3)

print(numbers.optionalFirst)// nil
print(numbers.middle)//"dos"
print(numbers.last)//3