println("There are \(naturalCount) stars in the Milky Way.")
// 输出 "There are hundreds of stars in the Milk Way."
在C语言中,通常使用break,避免执行了一个case语句后继续执行下一个case语句。在Swift语言中不需要添加break,switch语句只执行最前面一个符合条件的case语句。 case语句可以接类似于1...3的区间。 case语句可以接多个情况,用逗号隔开,switch value { case value1, value2: statements }
元组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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"
```
元组也可以用来判断条件,`_`用来匹配所有可能的值,也就是需要忽略的值。
## 值绑定
``` swift
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)")
caselet (x, y):
println("somewhere else at (\(x), \(y))")
}
case语句中,可以用临时的常量变量去绑定值并使用。
额外条件(Where语句)
1
2
3
4
5
6
7
8
9
10
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
caselet (x, y) where x == y:
println("(\(x), \(y)) is on the line x == y")
caselet (x, y) where x == -y:
println("(\(x), \(y)) is on the line x == -y")
caselet (x, y):
println("(\(x), \(y)) is just some arbitrary point")