什么是元组

元组将多个值分组为单个复合值。元组中的值可以是任何类型,并且不必彼此具有相同的类型。

通过对任意数量的值进行分组来创建元组:

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