《Swift从入门到精通》(二十五):模式匹配
2021-10-22 本文已影响0人
萧1帅
模式(Pattern)
什么是模式?
模式是用于匹配的规则,比如switch的case、捕捉错误的catch、if\guard\while\for语句的条件等
Swift中的模式有
- 通配符模式
- 标识符模式
- 值绑定模式
- 元组模式
- 枚举case模式
- 可选模式
- 类型转换模式
- 表达式模式
1.通配符模式(Wildcard Pattern)
- _ 匹配任意值
- _? 匹配非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, _):
print("human", name)
case .animal(let name, _?):
print("animal", name)
default:
print("other")
}
}
check(.human(name: "Rose", age: 20)) //human Rose
check(.human(name: "Jack", age: nil)) //human Jack
check(.animal(name: "Dog", age: 5)) //animal Dog
check(.animal(name: "Cat", age: nil)) //other
标识符模式(Identifier Pattern)
给对应的变量、常量名赋值
var age = 10
let name = "jack"
值绑定模式(Value-Binding Pattern)
let point = (3, 2)
switch point {
case let (x, y):
print("the point is at (\(x), \(y)")
}
元组模式(Tuple Pattern)
let points = [(0, 0), (1, 0), (2, 0)]
for (x, _) in points {
print(x)
}
let name: String? = "jack"
let age = 18
let info: Any = [1, 2]
switch (name, age, info) {
case (_?, _, _ as String):
print("case")
default:
print("default")
}//default
var scores = ["jack": 98, "rose": 100, "kate":86]
for (name, score) in scores {
print(name, score)
}
/*rose 100
kate 86
jack 98
*/
枚举case模式
if case 语句等价与只有1个case的switch语句
let age = 2
//原来的写法
if age >= 0 && age <= 9 {
print("[0, 9]")
}
//枚举case模式
if case 0...9 = age {
print("[0, 9]")
}
guard case 0...9 = age else {
return
}
print("[0, 9]")
switch age {
case 0...9:
print("[0, 9]")
default:
break
}
let ages: [Int?] = [2, 3, nil, 5]
for case nil in ages {
print("有nil值")
break
}// 有nil值
let points = [(1, 0), (2, 1), (3, 0)]
for case let (x, 0) in points {
print(x)
}// 1 3
可选模式(optional pattern)
let age: Int? = 42
if case .some(let x) = age {
print(x)
}
if case let x? = age {
print(x)
}
let ages: [Int?] = [nil, 2, 3, nil, 5]
for case let age? in ages {
print(age)
}// 2 3 5
for item in ages {
if let age = item {
print(age)
}
}// 跟上面的for,效果是等价的
类型转换模式(type-casting pattern)
let num: Any = 6
switch num {
case is Int:
print("is int", num)
default:
break
}
class Animal {
func eat() {
print(type(of: self), "eat")
}
}
class Dog: Animal {
func run() {
print(type(of: self), "run")
}
}
class Cat: Animal {
func jump() {
print(type(of: self), "jump")
}
}
func check(_ animal: Animal) {
switch animal {
case let dog as Dog:
dog.eat()
dog.run()
case is Cat:
animal.eat()
default:
break
}
}
// Dog eat
// Dog run
check(Dog())
//Cat eat
check(Cat())
表达式模式(expression pattern)
表达式模式用在case中
let point = (1, 2)
switch point {
case (0, 0):
print("(0, 0) is at origin.")
case (-2...2, -2...2):
print("(\(point.0), \(point.1) is near the origin")
default:
print("the point is at (\(point.0), \(point.1)")
}// (1, 2) is near the origin
自定义表达式模式
可以通过重载运算符,自定义表达式模式的匹配规则
struct Student {
var score = 0, name = ""
static func ~= (pattern: Int, value: Student) -> Bool {
value.score >= pattern
}
static func ~= (pattern: ClosedRange<Int>, value: Student) -> Bool {
pattern.contains(value.score)
}
static func ~= (pattern: Range<Int>, value: Student) -> Bool {
pattern.contains(value.score)
}
}
var stu: Student = Student(score: 75, name: "jack")
switch stu {
case 100:
print(">=100")
case 90:
print(">=90")
case 80..<90:
print("[80, 90)")
case 60...79:
print("[60, 79]")
default:
break
}// [60, 79]
if case 60 = stu {
print(">=60")
}// >=60
var info = (Student(score: 70, name: "jack"), "及格")
switch info {
case let (60, text):
print(text)
default:
break
} // 及格
where
可以使用where为模式匹配增加匹配条件
var data = (10, "jack")
switch data {
case let (age, _) where age > 10:
print(data.1, "age > 10")
case let (age, _) where age > 0:
print(data.1, "age > 0")
default:
break
}