swift(2)元祖(Tuple)

时间:2024-04-12 12:07:48
let somePoint = (, )

switch somePoint {
case (, ): // 位于远点
println("(0, 0) is at the origin")
case (_, ): // x为任意值,y为0,即在 X 轴上
println("(\(somePoint.0), 0) is on the x-axis")
case (, _): // y为任意值,x为0,即在 Y 轴上
println("(0, \(somePoint.1)) is on the y-axis")
case (-..., -...): // 在以原点为中心,边长为4的正方形内。
println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}

元组是多个值组合而成的复合值。元组中的值可以是任意类型,而且每一个元素的类型可以是不同的

1)给定元组元素命名,然后通过名称获取值(元组.名称)

let http200Status = (statusCode: , description: "OK")
println("The status code is \(http200Status.statusCode)")
println("The status message is \(http200Status.description)")

结果:200

   OK

2)通过下标获取,从0开始

let http404Error = (, "Not Found")
// 通过元组.0获取第二个值
println("The status code is \(http404Error.0)")
// 通过元组.1获取第二个值
println("The status message is \(http404Error.1)")

参考:http://blog.csdn.net/woaifen3344/article/details/29357261

明日计划--看函数和闭包