~~~
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)