美文网首页
Swift语法 -- [22 - 模式匹配]

Swift语法 -- [22 - 模式匹配]

作者: happy神悦 | 来源:发表于2020-11-02 09:15 被阅读0次

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

Swift中的模式有:

  • 通配符模式 (Wildcard Pattern)
  • 标识符模式 (Identifier Pattern)
  • 值绑定模式 (Value-Binding Pattern)
  • 元组模式 (Tuple Pattern)
  • 枚举Case模式 (Enumeration Case Pattern)
  • 可选模式 (Optional Pattern)
  • 类型转换模式 (Type-Casting Pattern)
  • 表达式模式 (Expression Pattern)

1. 通配符模式 (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, _):
    print("human", name)
  case .animal(let name, _?):
    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

2. 标识符模式 (Identifier Pattern)

//给对应的变量、常量名赋值
var age = 10
let name = "jack"

3. 值绑定模式 (Value-Binding Pattern)

let point = (3, 2)
switch point {
case let (x, y):
  print("The point is at(\(x),\(y)).")
}

4. 元组模式 (Tuple Pattern)

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

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

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

5. 枚举Case模式 (Enumeration Case Pattern)

/* if case语句等价于只有1个case的switch语句 */
let age = 2
// 原来的写法
if age >= 0 && age <= 9 {
  print("[0, 9]")
}
// 枚举用例模式
if case 0...9 = age {//判断age是否在0..9区间内
  print("[0, 9]")
}
guard case 0...9 = age else { return }
print("[0, 9]")


switch age {
case 0...9: print("[0, 9]")
default: break
}

let ages: [Int?] = [2, 3, nil, 5]
for case nil in ages {//拿出数组ages里的每一个值,与case进行匹配,如果有nil就执行里面的语句
  print("有nil值")
  break
}// 有nil值


let points = [(1, 0), (2, 1), (3, 0)]
for case let (x, 0) in points {//匹配出points里面y为0的元素
  print(x)
}// 1 3

6. 可选模式 (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
/// 跟上面👆的for, 效果是等价的
let ages: [Int?] = [nil, 2, 3, nil, 5]
for item in ages {//这样写不简洁, 不如上面的匹配模式
  if let age = item {
    print(age)
  }
} 

func check(_ num: Int?) {
  switch num {
  case 2?: print("2")//非空, 传2时执行
  case 4?: print("4")
  case 6?: print("6")
  case _?: print("other")//只要为非空, 都可以
  case _: print("nil")//不管是空还是非空,都可以
  }
}
check(4) // 4
check(8) // other
check(nil) // nil


/* 回忆补充: */
var age: Int? = 10
switch age {
case let x?:
  print(x)
case nil:
  print("nil")
}
//等价于👆
switch age {
case .some(let x):
  print(x)
case .none:
  print("nil")
}

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

let num: Any = 6
switch num {
case is Int:
    // 编译器依然认为num是Any类型
  print("is Int", num)
// case let n as Int://把n强转为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强转为Dog类型, 不会对animal造成影响
    dog.eat()
    dog.run()
  case is Cat:// 判断是不是Cat类型
    animal.eat()
  default: break
  }
}
// Dog eat
// Dog run
check(Dog())
// Cat eat
check(Cat())

8. 表达式模式 (Expression Pattern)

/* 表达式模式用在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.


/* 自定义表达式模式 一 */
/// 可以通过重载运算符, 自定义表达式模式的匹配规则
struct Struct {
    var score = 0, name = ""
  // pattern: case后面的内容, value: switch后面的内容
  static func ~= (pattern: Int, value: Student) -> Bool { value.score >= pattern }
  static func ~= (pattern: ClosedRange<Int>, value: Student) -> Bool { pattern.contains(value.score) }
  static func ~= (pattern: Range<Int>, value: Student) -> Bool { pattern.contains(value.score) }
}

var stu = Student(score: 75, name: "Jack")
switch stu {// 通过自定义表达式, 实现stu与范围值进行匹配
case 100: print(">= 100")
case 90: print(">= 90")
case 80..<90: print("[80, 90)")
case 60...79: print("[60, 70]")
case 0: print(">= 0")
default: break
}// [60, 79]

if case 60 = stu {
  print(">=60")
}// >=60

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

/* 自定义表达式模式 二 */
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 = "jack"
switch str {
case hasPrefix("j"), hasSuffix("k"): // (String) -> Bool
  print("以j开头, 以k结尾")
default: break
}// 以j开头, 以k结尾


/* 自定义表达式模式 三 */
func isEven(_ i: Int) -> Bool { i % 2 == 0 }
func isOdd(_i: Int) -> Bool { i % 2 != 0 }

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

var age = 9
switch age {
case isEvent://case后面放的是函数类型, 不是在调用函数
  print(age, "是个偶数")
case isOdd:
  print(age, "是个奇数")
default: break
}


/* 自定义表达式模式 四 */
prefix operator ~>
prefix operator ~>=
prefix operator ~<
prefix operator ~<=
prefix func ~> (_ i: Int) -> ((Int) -> Bool) { { $0 > i } }
prefix func ~>= (_ i: Int) -> ((Int) -> Bool) { { $0 >= i } }
prefix func ~< (_ i: Int) -> ((Int) -> Bool) { { $0 < i } }
prefix func ~<= (_ i: Int) -> ((Int) -> Bool) { { $0 <= i } }

var age = 9
switch age {
case ~>=0:
print("1")
case ~>10:
print("2")
default: break
} // [0, 10]

9. where

/* 可以使用where为模式匹配增加匹配条件 */
var data = (10, "Jack")
switch data {
case let (age, _) where age > 10:
print(data.1, "age>10")
case let (age, _) where age > 0:
print(data.1, "age>0")
default: break
}

var ages = [10, 20, 44, 23, 55]
for age in ages where age > 30 {
print(age)
} // 44 55

protocol Stackable { associatedtype Element }
protocol Container {
associatedtype Stack : Stackable where Stack.Element : Equatable
}

func equal<S1: Stackable, S2: Stackable>(_ s1: S1, _ s2: S2) -> Bool
where S1.Element == S2.Element, S1.Element : Hashable {
return false
}

extension Container where Self.Stack.Element : Hashable { }

相关文章

  • Swift语法 -- [22 - 模式匹配]

    模式是用于匹配的规则, 比如switch的case、捕捉错误的catch、if\guard\while\for语句...

  • Swift中强大的模式匹配

    Swift中的模式匹配语法是一个亮点,Swift里switch比OC里面强大很多,switch的主要特性就是模式匹...

  • ios 经典面试案例 (七)

    Swift有哪些模式匹配? 模式匹配总结: 1.通配符模式(Wildcard Pattern)如果你在 Swift...

  • 22-Swift模式匹配

    1.模式(Pattern) 什么是模式?模式是用于匹配的规则,比如switch的case、捕捉错误的catch、i...

  • Swift 中的 as、as! 和 as?

    1. 关于as 将子类转换为基类 数值类型转换 switch 中的模式匹配 Swift中可以通过switch语法检...

  • 在Swift里的自定义模式匹配(译)

    原文地址模式匹配在swift里是随处可见的,虽然switch case是匹配模式最常见的用法,但是Swift有多种...

  • Swift-模式匹配

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

  • Swift 模式匹配总结

    Swift 模式匹配总结 基本用法 对枚举的匹配: 在swift中 不需要使用break跳出当前匹配,默认只执行一...

  • Swift中的模式匹配

    模式匹配 模式匹配是 Swift 中非常常见的一种编程模式,使用模式匹配,可以帮助我们写出简明、清晰以及易读的代码...

  • scala(二十一) 模式匹配(match)

    前言 Scala中的模式匹配类似于Java中的switch语法,但是更加强大。模式匹配语法中,采用match关键字...

网友评论

      本文标题:Swift语法 -- [22 - 模式匹配]

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