Swift语法基础:18 - Swift的元组, 绑定值, Where
好了, 下面让我们继续往下看吧:
1.元组
你可以使用元组在同一个 switch 语句中测试多个值。元组中的元素可以是值,也可以是范围。另外,使用下划线( _ )来匹配所有可能的值。
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
println("(0, 0)is at the origin")
case (_, 0):
println("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
println("0, \(somePoint.1) is on the y-axis")
case (-2...2, -2...2):
println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
//打印出来的结果: (1, 1) is inside the box
2.绑定值
case 块的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 块 里就可以被引用了——这种行为被称为值绑定。
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
println("on the x-axis with an x value of \(x)")
case (0, let y):
println("on the y-axis with a y value of \(y)")
case let (x, y):
println("somewhere else at (\(x), \(y))")
}
// 打印出来的结果: on the x-axis with an x value of 2
3.Where
case 块的模式可以使用 where 语句来判断额外的条件。当且仅当 where 语句的条件为真时,匹配到的 case 块才会被执行。
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
println("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
println("(\(x), \(y)) is just some arbitrary point")
}
// 打印出来的结果: (1, -1) is on the line x == -y
好了, 这次就讲到这里, 下次我们继续~