Where

340 查看

“case 分支的模式可以使用where语句来判断额外的条件。”

“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")
}”

“这三个 case 都声明了常量x和y的占位符,用于临时获取元组yetAnotherPoint的两个值。这些常量被用作where语句的一部分,从而创建一个动态的过滤器(filter)。当且仅当where语句的条件为true时,匹配到的 case 分支才会被执行。”