美文网首页
Swift-模式匹配

Swift-模式匹配

作者: Sweet丶 | 来源:发表于2022-12-16 16:46 被阅读0次

模式就是匹配的规则,下面介绍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的使用场景

相关文章

  • Swift-模式匹配

    模式就是匹配的规则,下面介绍Swift中的模式。 1. 通配符模式 _匹配任何值,_?匹配非nil值。 2. 标识...

  • 模式匹配

    模式匹配之字符串 模式匹配之匹配类型 模式匹配之匹配数组、元组、集合 模式匹配之样例类 模式匹配之偏函数

  • 多模式串匹配 - AC 自动机

    多模式串匹配概念 多模式串匹配,即多个模式串在一个主串中进行匹配。 虽然单模式串也能完成多模式串的匹配,但每个模式...

  • Scala模式匹配

    模式匹配match 模式匹配不仅可以匹配值(case 1)还可以匹配类型(case s:String) 匹配过程有...

  • 正则表达式懒惰型元字符匹配 ?

    懒惰匹配模式即表示以最少的匹配量返回匹配个数,默认是非懒惰匹配模式 表达式 匹配结果:

  • scala 模式匹配的几个模式

    Scala 的模式匹配是类似与正则匹配的的模式匹配,但是不仅仅如此,它还可以匹配对象的内在的构建形式. 模式匹配就...

  • 模式匹配

    模式匹配 sql模式匹配允许使用"_"匹配任何单个字符,"%"匹配任意数目字符(包括零字符)。使用sql模式时,不...

  • Scala中的模式匹配

    简单匹配 模式匹配常用于match语句: 变量使用 模式匹配case中可以使用变量来获取参数值 类型匹配 守卫匹配...

  • web开发常识

    .gitignore规则 匹配模式前 / 代表项目的根目录 匹配模式最后加 / 代表是目录 匹配模式前加!代表取反...

  • 模式匹配

    模式 模式类型 通配符模式 _ 匹配任何值 _? 匹配非nil值 标识符模式 值绑定模式 元组模式 枚举case模...

网友评论

      本文标题:Swift-模式匹配

      本文链接:https://www.haomeiwen.com/subject/ybemfdtx.html