23-模式匹配

127 阅读4分钟

模式匹配(Pattern)

模式是用于匹配的规则,比如 switch 的 case、捕捉错误的 catch、if / guard / while / for 语句的条件等。

Swift中的模式有以下几种:

  1. 通配符模式(Wildcard Pattern)
  2. 标识符模式(Identifier Pattern)
  3. 值绑定模式(Value-Binding Pattern)
  4. 元组模式(Tuple Pattern)
  5. 枚举Case模式(Enumeration Case Pattern)
  6. 可选模式(Optional Pattern)
  7. 类型转换模式(Type-Casting Pattern)
  8. 表达式模式(Expression Pattern)

通配符模式

通配符模式使用 _ 来匹配任何值(包括nil),使用 _? 来匹配非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, _?):        // _? 匹配非nil值
        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

标识符模式

标识符模式是给对应的常量,变量名赋值

var age = 25
let name = "Alice"

值绑定模式

值绑定模式将匹配的值绑定到变量或常量。

let point = (3, 4)

switch point {
case let (x, y):
    print("Point at (\(x), \(y))")
}

元组模式

元组模式用于匹配元组值。

我自己的理解就是用(a,b)这样的一个东西去匹配一些值,然后拿着这个值进行后续处理

  1. 在 for 循环中使用元组模式
let points = [(0, 0), (1, 0), (2, 0)]
for (x, _) in points {
    print(x)
}
  1. 在 switch 中使用元组模式
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
  1. 字典遍历中的元组模式
var scores = ["jack": 98, "rose": 100, "kate": 86]
for (name, score) in scores {
    print(name, score)
}

枚举 Case 模式(Enumeration Case Pattern)

if case 语句等价于只有一个 case 的 switch 语句,所以switch中的case能怎么写,if case也能怎么写

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
}

上面的if case 和这里的switch case是完全一样的,相当于写了switch case

let ages: [Int?] = [2, 3, nil, 5]
for case nil in ages {
    print("有nil值")
    break
} // 有nil值

也可以想象case nil 是放在switch case 里面

let points = [(1, 0), (2, 1), (3, 0)]
for case let (x, 0) in points {
    print(x)
} // 1 3

也可以想象case nil 是放在switch case 里面

可选模式(Optional Pattern)

可选模式用于匹配可选值,啥是可选值,可选值就是可以为nil的值。

let age: Int? = 42
// 可选形其实是个枚举值 .some .none
// 不为nil就能匹配,绑定到x
if case .some(let x) = age { print(x) }
// 所有的age值都能匹配到x上,包括nil
if case let x? = age { print(x) }
// ages是一个装着Int的数组
let ages: [Int?] = [nil, 2, 3, nil, 5]
for case let age? in ages {
    print(age)
}
// 2 3 5
let ages: [Int?] = [nil, 2, 3, nil, 5]
for item in ages {
    if let age = item {
        print(age)
    }
}
// 跟上面的 for,效果是等价的
func check(_ num: Int?) {
    switch num {
    // 为啥这里是 2? 不是2 呢,因为num是可选类型,他实际只能匹配的值是 .some(2),不能匹配2,.some(2)可以用 2?代表
    case 2?: print("2")
    case 4?: print("4")
    case 6?: print("6")
    case _?: print("other")
    case _: print("nil")
    }
}

check(4)   // 4
check(8)   // other
check(nil) // nil

类型转换模式(Type-Casting Pattern)

类型转换模式用于类型检查和转换。 is 是判断是不是,但是不对原类型做转化,而as是直接做转化。

let num: Any = 6
switch num {
case is Int:
    // 编译器依然认为 num 是 Any 类型
    print("is Int", num)
//case let n as Int:
//    print("as Int", n + 1)
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()
        // 由于这里不做转化,所以下面的animal还是animal类型,不能直接调Cat的方法
    case is Cat:
        animal.eat()
    default:
        break
    }
}

// Dog eat
// Dog run
check(Dog())

// Cat eat
check(Cat())

表达式模式

表达式模式用在 case 中,通过表达式(如范围、函数)来决定匹配逻辑。

let point = (1, 2)
switch point {
case (0, 0):
    print("(0, 0) is at the 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.