不用再写break,匹配到就返回
不再有之前的case 穿透 但是可以逗号分割,但是每一个case的函数体必须要包含至少一个可执行的语句
在一个switch的case中匹配多个值可以用逗号分割,并且可以写成多行
//: A UIKit based Playground for presenting user interface
import UIKit
let a:Character = "a"
switch a {
case "a","A":
print("the letter A or a")
default:
print("the letter other")
}
switch 的case 的值可以在一个区间中匹配
//: A UIKit based Playground for presenting user interface
import UIKit
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var natrualCount:String
switch approximateCount {
case 0:
natrualCount = "no"
case 1..<5:
natrualCount = "a few"
case 5..<12:
natrualCount = "several"
case 12..<100:
natrualCount = "donzens of"
case 100..<1000:
natrualCount = "hundreds of"
default:
natrualCount = "Manyy"
}
元祖匹配
你可以用元祖在一个switch 语句中测试多个值
使用下划线(_)来表示所有可能的值
code
//: A UIKit based Playground for presenting user interface
import UIKit
let somePoint=(1,1)
switch somePoint {
case (0,0):
print("is at the origin")
case (_,0):
print("(\(somePoint.0),0)is on the x-axis")
case (0,_):
print("0,(\(somePoint.0))is on the Y-axis")
case (-2...2,-2...2):
print("(\(somePoint.0),\(somePoint.1)) is inside the box")
default:
print("(\(somePoint.0),\(somePoint.1)) is outside of the box")
}
(1,1) is inside the box
这可以理解为一个方框4*4的方框 -2...2
值绑定
siwtch 和case 可以将匹配到的值临时绑定为一个常量或者变量。来给case的函数体使用
如果使用var 关键字 ,临时的遍历就会以和值的值来创建并初始化,对这个遍历的任何改变都智慧在case的函数体内有效
code
//: A UIKit based Playground for presenting user interface
import UIKit
let somePoint=(2,0)
switch somePoint {
case (let x,0):
print("on the x axis with an x value of \(x)")
case (0,let y):
print("on the y-axis with an x value of \(y)")
case (let x, let y):
print("somewhere else at (\(x),\(y))")
}
somewhere else at (2,0)
更牛逼的可以添加where
可能工程师觉得where还是不够强大。
于是乎。。。
switch case 可以使用where分句来检索是否符合特定的约束
//: A UIKit based Playground for presenting user interface
import UIKit
let somePoint=(2,-2)
switch somePoint {
case let(x,y) where 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")
}
(2,-2)is on the line x == -y