元组
元组(tuples)是由其它类型组合而成的类型。元组可能包含零或多个类型,比如 字符串、整数、字符、布尔以及其它元组。同时请注意,元组是值传递,而不是引用。
在Swift中创建元组的方式很简单,元组类型是用括号包围,由一个逗号分隔的零个或多个类型的列表。例如:
let firstHighScore = ("Mary", 9001)
另外,在创建元组时你还可以给元组中的元素命名:
let secondHighScore = (name: "James", score: 4096)
以上就是创建元组的两种方式,非常简单和简洁。你不需要像创建struct一样写出它的结构和内部属性,也不需要像创建class一样要写初始化方法。你只需要把你想用的、任何类型的值放在圆括号内,用逗号隔开即可。如果你愿意你还可以给每个元素命名,提高元组使用效率。
从元组中读元素
如果我们没有给元组的元素命名,我们可以用点语法,通过定义好的元组变量或常量获取它的第1个到第n个元素:
let firstHighScore = ("Mary", 9001)
println(firstHighScore.0) // Mary
println(firstHighScore.1) // 9001
如果你觉得上述这种方法会造成语义的不明确,那么我们还可以将元组赋值给一个带有元素名称的元组(元素名称个数要对应):
let (firstName, firstScore) = firstHighScore
println(firstName) // Mary
println(firstScore) // 9001
如果你只需要一部分元组值,分解的时候可以把要忽略的部分用下划线(_)标记:
let (_, firstScore) = firstHighScore
println(firstScore) // 9001
如果我们已经给元组中的元素命名了名称,那么我们可以这样写:
let secondHighScore = (name: "James", score: 4096)
println(secondHighScore.name) // James
println(secondHighScore.score) // 4096
将元组作为函数返回值
当你想让一个函数能够返回多种类型时,这是元组的最佳使用场景。
我们可以将元组作为函数的返回值,下面这个函数的返回值就是我们之前定义过的secondHighScore元组:
func getAHighScore() -> (name: String, score: Int) {
let theName = "Patricia"
let theScore = 3894
return (theName, theScore)
}
为什么说上述函数的返回值是secondHighScore元组呢?因为getAHighScore函数返回的元组元素个数、元素名称、元素类型均和secondHighScore相同。
其实将元组作为函数的返回值时也可以不必对元素进行命名,只要你明白每个元素代表的含义即可:
func getAHighScore() -> (String, Int) {
let theName = "Patricia"
let theScore = 3894
return (theName, theScore)
}








