Swift-模式匹配

模式就是匹配的规则,下面介绍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模式
  1. if case语句等价于只有一个caseswitch语句。下面三种方式结果是一样的。
    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. 类型转换模式

主要是通过isas来判断类型是否匹配

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的使用场景

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章