Swift-模式匹配 Pattern Matching

27 阅读2分钟

~=

Pattern Matching

developer.apple.com/documentati…::)

pattern-matching-in-swift

Swift 最佳实践之 Pattern Matching

[译] Swift 中强大的模式匹配


在Swift中,模式匹配(Pattern Matching)是用来检查数据类型或数据结构是否符合某种模式的机制。它是Swift语言的一个强大特性,广泛用于switch语句、if case语句、解构赋值等场景。通过模式匹配,可以更轻松地处理不同类型和结构的数据。

常见的模式匹配类型

  1. 常量匹配: 用来匹配具体的值或常量。

    let number = 42
    switch number {
    case 42:
        print("Matched the number 42!")
    default:
        print("Not matched.")
    }
    
  2. 类型匹配: 通过isas关键字来匹配对象的类型。

    let value: Any = "Hello, Swift!"
    if case let str as String = value {
        print("It's a string: \(str)")
    }
    
  3. 范围匹配: 匹配一个数值范围,可以是闭区间或半开区间。

    let number = 25
    switch number {
    case 1...10:
        print("In the range 1 to 10")
    case 11..<20:
        print("In the range 11 to 19")
    case 20...30:
        print("In the range 20 to 30")
    default:
        print("Out of range")
    }
    
  4. 元组匹配: 可以同时匹配多个值,类似于解构赋值。

    let point = (x: 1, y: 2)
    switch point {
    case (0, 0):
        print("Origin")
    case (let x, 0):
        print("On the x-axis at \(x)")
    case (0, let y):
        print("On the y-axis at \(y)")
    default:
        print("A point somewhere else")
    }
    
  5. 可选值匹配: 用于解包可选类型。

    let name: String? = "Alice"
    if case let name = name {
        print("Name is \(name)")
    }
    
  6. 带条件的匹配: 可以添加附加条件来进一步筛选匹配。

    let number = 42
    switch number {
    case let x where x % 2 == 0:
        print("Even number: \(x)")
    default:
        print("Not an even number")
    }
    

使用if case进行模式匹配

除了switch语句,Swift还允许在if case语句中进行模式匹配,通常用于检查值并执行特定的代码块。

let number: Int? = 5
if case let n? = number, n > 0 {
    print("Positive number: \(n)")
}

总结

Swift中的模式匹配是通过多种方式(如常量、类型、范围、元组、可选值等)来匹配不同的数据结构和类型。它是Swift中非常有用的功能,使得代码更加简洁和易于维护。