模式就是匹配的規則,下面介紹Swift中的模式。
1. 通配符模式
_
匹配任何值,_?
匹配非nil值。
// 通配符模式
enum Life {
case human(name: String, age: Int?)
case animal(name: String, age: Int?)
}
func check(_ life: Life) {
switch life {
case .human(let name, _): //這裏的“_”的意思是age是任何值都可以
print("human: \(name)")
case .animal(let name, age: _?)://這裏的“_?”的意思是age非nil才匹配
print("animal: \(name)")
default:
print("other")
}
}
2. 標識符模式
給對應的變量、常量賦值
var age = 10
let name = "dandy"
3. 值綁定模式
將匹配的值綁定到對應的變量上, 例如下面的元組的值分別綁定到x,y中
let point = (4, 5)
switch point {
case let (x, y):
print("point.x: \(x), .y: \(y)")
}
4. 元組模式
通過元組類型來匹配,並將匹配的值綁定到對應的位置。
let points = [(0, 0), (0, 1), (0, 2)]
for (x, _) in points {
print(x)
}
// 將多個值的判斷通過元組來匹配
let name: String? = "dandy"
let age = 18
let info: Any = [1, 2]
switch (name, age, info) {
case (_?, _, _ as String):
print("case")
default:
print("default")
}
var scores = ["jack" : 98,"rose": 100, "kate": 59]
for (name, score) in scores {
print(name, score)
}
5. 枚舉case模式
-
if case
語句等價於只有一個case
的switch
語句。下面三種方式結果是一樣的。
let age = 2
if age >= 0 && age <= 9 {
print("方式1:0~9之內")
}
// 枚舉case模式
if case 0...9 = age {
print("方式2:0~9之內")
}
switch age {
case 0...9:
print("方式3:0~9之內")
default: break
}
2.for case
的方式來查找匹配的case
let ages = [1, 5, nil, 9]
for case nil in ages {
print("有nil")
}// 有nil
let points = [(1, 2), (33, 44), (55, 2)]
for case let (x, 2) in points {
print(x)
} // 1 55
6. 可選模式
用來匹配非空或空
func testPatternCase3() {
let age: Int? = 30
// 方式1
if case .some(let wrapped) = age {
print(wrapped) // 30
}
// 方式2
if case let x? = age {
print(x) // 30
}
// 3.for循環中匹配非空
let ages = [1, 5, nil, 9]
for case let age? in ages {
print(age)
}// 1 5 9
// 4.非空特定指的匹配
let a: Int? = 4
let b = 4
let c: Int? = nil
checkCase(a) // 4
checkCase(b) // 4
checkCase(c) // nil
}
func checkCase(_ num: Int?) {
switch num {
case 2?: print("2") // 非空的2
case 3?: print("3")// 非空的3
case 4?: print("4")// 非空的4
case _?: print("other")// 非空的其他值
case _: print("nil") // 爲nil
}
}
7. 類型轉換模式
主要是通過is
和as
來判斷類型是否匹配
func testPatternCasting() {
// 下面兩個case都是可以通用的
let num: Any = 5
switch num {
// case is Int:// Int類型,會來到這裏
// print("num is Int")
case let n as Int:// 能轉換爲Int類型,也會來到這裏
print("num can casting to Int: \(n)")
default: break
}
// 用來判斷類型
testPatternCasting2(Animal1()) // 不打印
testPatternCasting2(Dog2()) // "Dog2 eat" "Dog2 run"
testPatternCasting2(Cat3()) // Cat3 eat
}
func testPatternCasting2(_ animal: Animal1) {
switch animal {
case let dog as Dog2:
dog.eat()
dog.run()
case is Cat3:
animal.eat()
default: break
}
}
class Animal1 { func eat() { print(type(of: self), "eat") } }
class Dog2 : Animal1 { func run() { print(type(of: self), "run") } }
class Cat3: Animal1 { func jump(){ print(type(of: self), "jump") } }
8. 表達式模式
表達式模式通過運算符重載來自定義case匹配規則。
func testPatternExpression() {
let stu = Students(score: 85, name: "dandy")
switch stu {
case 100: print(">= 100")
case 80..<90: print("[80, 90)")
case 0: print(">=0")
default: break
}// 結果:[80, 90)
if case 60 = stu {
print(stu.name, ">=60")
}// 結果:dandy >=60
}
struct Students {
var score = 0, name = ""
static func ~=(pattern: Int, value: Students) -> Bool {
return value.score >= pattern
}
static func ~=(pattern: ClosedRange<Int>, value: Students) -> Bool {
return pattern.contains(value.score)
}
static func ~=(pattern: Range<Int>, value: Students) -> Bool {
return pattern.contains(value.score)
}
}
9. 使用where爲模式匹配增加條件
具體使用見Swift中where的使用場景