~~~
import Foundation
let point = (2, 2)
switch point {
case (0, 0):
print("point is (0, 0)")
case (_, 0): //_匹配所有可能的值
print("point is (_, 0)")
case (0, _):
print("point is (0, _)")
case (0...3, 0...3):
print("point is the scope of (0...3, 0...3)")
default:
print("not in the scope of ... ")
}
//值綁定
//case 分?的模式允許將匹配的值綁定到?個臨時的常量或變量,這些常量或變量在該
//case 分??就可以被引?了——這種?為被稱為值綁定(value binding)。
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0): //匹配縱坐標是0的點,并將橫坐標的值賦予x,下同
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y): //匹配所有
print("somewhere else at (\(x), \(y))")
}
//case分支的模式可以使用where語句來判斷額外的條件
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y: //匹配x等于y的所有情況,下同
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
~~~
輸出:
~~~
point is the scope of (0...3, 0...3)
on the x-axis with an x value of 2
(1, -1) is on the line x == -y
Program ended with exit code: 0
~~~
- 前言
- swift控制語句,for,while,repeat-while,if,switch
- swift之聲明常量和變量
- swift之數值類型雜談(數值)
- swift之 元組
- oc與swift混編,OC調用swift,swift調用OC
- swift之可選類型
- swift之數組(Array)、集合(Set)、字典(Dictionary)
- swift之switch續(元組,值綁定,where)
- swift之控制轉移語句,continue,break,fallthrough,return,帶標簽的語句
- swift之函數(functions)
- swift之閉包(closure)
- swift之枚舉
- swift之類和結構體
- swift之屬性
- swift之方法(Methods)