元组是多个数据的组合,用()包围。元组中的数据可以是任何的类型。
元组可以被解构
let http404Error = (404, "Not Found") //定义了一个数组
let (statusCode, statusMessage) = http404Error // 因为是decompose,所以⚠️顺序不能倒。
print("The status code is \(statusCode)")
// The status code is 404
print("The statusMessage is \(statusMessage)")
//The statusMessage is Not Found
解构的时候,如果你需要的只是部分数据,可以用underscore_来掩盖那些你不需要的数据
let http404Error = (404, "Not Found") //定义了一个数组
let (statusCode, _) = http404Error
print("\(statusCode)")
访元组中的数据
使用元素的位置。与反问数组中的元素不同的地方在于,它这里用的是.
let person = ("Alice", 30, 5.8)
print(person.0)
// Alice
为了更清晰的访问元组的中值,可以为元组中的元素命名。相当于字典里通过‘键‘访问’值‘。不同的是这里还是用.来访问。
let person = (name: "Alice", age: 30, height: 5.8)
print(person.height)
// 5.8
在函数中使用元组
元组最明显的优势在于它可以允许函数有多个返回值。
func minMax (array: [Int]) -> (min: Int, max: Int) { // 创建了一个函数,参数类型为数组,返回值类型为元组
var currentMin = 0
var currentMax: Int = 0
for element in array[0..<array.count] {
if element < currentMin {
currentMin = element
} else if element > currentMax {
currentMax = element
}
}
return (currentMin, currentMax) // 返回了一个元组. 注意这里顺序要和函数定义里的元组定义相同。
}
let bounds = minMax(array: [8, -6, 2, 109, 3, 71])
print("Min: \(bounds.min); Max: \(bounds.max)") // 因为我们已经在函数返回值中为元组成员进行了命名,这里可以通过dot syntax进行访问。