Swift5.1学习随笔之模式匹配Pattern

  • 模式是用于匹配的规则,比如switchcase、捕捉错误的catchif gurad while for语句的条件等
  • Swfit中的模式有:
    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)

通配符模式(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, _): //满足human,age可以为nil
        print("human", name)
    case .animal(let name, _?): //满足animal且age不可以为nil
        print("animal", name)
    default:
        print("other")
    }
}
check(.human(name: "Rose", age: 20)) // human Rose
check(.human(name: "Jacl", age: nil)) // human Jacl
check(.animal(name: "Dog", age: 3)) // 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)")
}

这里就是把元组中的3赋值绑定给x,把2赋值绑定给y


元组模式(Tuple Pattern)

将数组内部元素通过元组进行遍历

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

将3个变量通过元组来进行匹配:

let name: String? = "jack"
let age = 18
let info: Any = [1, 3]
switch (name, age, info) {
case (_?, _, _ as String):
    print("case")
default:
    print("default")
} // default

一个字典通过元组进行遍历匹配

let scores = ["jack": 98, "rose": 100, "kate": 86]
for (name, score) in scores {
    print(name, score)
}

枚举Case模式(Enumeration Case Pattern)

if case语句等价于只有1caseswitch语句

let age = 2
//原来的写法
if age >= 0 && age <= 0 {
    print("[0, 9]")
}
//枚举case模式
if case 0...9 = age {
    print("[0, 9]")
}
//等价于只有1个case的这样写法
switch age {
case 0...9:
    print("[0, 9]")
default: break
}

匹配数组里面是否有nil

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

可选模式(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
func check(_ num: Int?) {
    switch num {
    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)
let num: Any = 6
switch num {
case is Int:
    print("is Int", num)
default:
    break
} // is Int 6 (这时候编译器仍然认为num是Any类型,并不会强转)

上面代码中编译器仍然认为numAny类型,并不会强转。

let num: Any = 6
switch num {
case let n as Int:
    print("is Int", n)
default:
    break
} // is Int 6

上面代码中的n此时是Int类型,但是num依然是Any类型
isas并不影响switch原本类型

class Animal {
    func eat() { print(type(of: self),"eat") }
}
class Dog: Animal {
    func run() { print(type(of: self),"run") }
}
class Cat: Animal {
    func run() { 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
    }
}
check(Dog()) // Dog eat , Dog run
check(Cat()) // Cat eat

表达式模式(Expression Pattern)
  • 表达式模式用在case中,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:
    break
} // (1, 2) is near the origin
  • 通过重载运算符,自定义表达式模式的匹配规则
    上面的代码case (-2...2, -2...2):通过断点查看汇编,可以看出编译器调用了~=运算符进行匹配。
struct Student {
    var score = 0, name = ""
}

var stu = Student(score: 75, name: "jack")
switch stu {
case 100: print(">= 100") // Expression pattern of type 'Int' cannot match values of type 'Student'
case 90: print(">= 90") // Expression pattern of type 'Range' cannot match values of type 'Student'
case 80..<90: print("[80, 90]") // Expression pattern of type 'Range' cannot match values of type 'Student'
case 60...79: print("[60, 79]") // Expression pattern of type 'ClosedRange' cannot match values of type 'Student'
case 0: print(">= 0") // Expression pattern of type 'Int' cannot match values of type 'Student'
default:
    break
}

上面的代码中,对Student变量进行匹配会报错,默认情况下,编译器无法对stu进行switch操作,因为匹配的条件类型不符合。
因此需要对Student类进行重载~=运算符:

struct Student {
    var score = 0, name = ""
    ///pattern:case后面的内容
    ///value:switch后面的内容
    static func ~=(pattern: Int, value: Student) -> Bool {
        value.score >= pattern
    }
    static func ~=(pattern: Range, value: Student) -> Bool {
        pattern.contains(value.score)
    }
    static func ~=(pattern: ClosedRange, value: Student) -> Bool {
        pattern.contains(value.score)
    }
}

还可以写成下面的样子:

if case 60 = stu {
    print("yes")
}

更多例子:Studentscore如果大于等于60,就匹配成功,输出text

var info = (Student(score: 65, name: "jack"), "及格")
switch info {
case let (60, text):
    print(text)
default:
    break
} // 及格

String增加一个匹配条件,符合switch匹配方式:

extension String {
    static func ~=(pattern: (String) -> Bool, value: String) -> Bool {
        pattern(value)
    }
}

func hasPrefix(_ prefix: String) -> ((String) -> Bool) {
    { $0.hasPrefix(prefix) }
}
func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
    { $0.hasSuffix(suffix) }
}

var str = "123456"
switch str {
case hasPrefix("123"): print("123开头")
case hasSuffix("456"): print("456结尾")
default:
    break
}

你可能感兴趣的:(Swift5.1学习随笔之模式匹配Pattern)