元组是多个值组合而成的复合值。元组中的值可以是任意类型,而且每一个元素的类型可以是不同的。
如:
// http404Error是(Int, String)类型 // 这个元组是二元组,是一个整型和字符串类型的组合,这里代表着404的意思是Not Found let http404Error = (404, "Not Found")
如:
let (statusCode, statusMessage) = http404Error // prints "The status code is 404" println("The status code is \(statusCode)") println("The status message is \(statusMessage)")
如:
let (statusCode, _) = http404Error println("The status code is \(statusCode)")
如:
let http404Error = (404, "Not Found") // 通过元组.0获取第二个值 println("The status code is \(http404Error.0)") // 通过元组.1获取第二个值 println("The status message is \(http404Error.1)")
访问元组元素还有一种方式:给定元组元素命名,然后通过名称获取值(元组.名称)
如:
let http200Status = (statusCode: 200, description: "OK") println("The status code is \(http200Status.statusCode)") println("The status message is \(http200Status.description)")