美文网首页
Swift基础知识之模式匹配

Swift基础知识之模式匹配

作者: alfei13 | 来源:发表于2021-05-24 13:16 被阅读0次

一、模式(Pattern)

  • 什么是模式?
    • 模式是用于匹配的规则,比如switch的case、不做错误的catch等
  • Swift中的模式有
    • 通配符模式(Wildcard Pattern)
    • 标志符模式(Identifier Pattern)
    • 值绑定模式(Value-Binding Pattern)
    • 元组模式(Tuple Pattern)
    • 枚举Case模式(Enumeration Case Pattern)
    • 可选模式(Optional Pattern)
    • 类型转换模式(Type-Casting Pattern)
    • 表达式模式(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, age: _):
        print("human", name)
    case .animal(let name, age: _?):
        print("animal", name)
    default:
        print("other")
    }
}

check(.human(name: "Haha", age: 20)) // human Haha
check(.human(name: "JJJ", age: nil)) // human JJJ
check(.animal(name: "Cat", age: nil)) // other

三、标志符模式(Identifier Pattern)

  • 给对应的变量、常量赋值
var age = 10
let name = "JJJ"

四、值绑定模式(Value-Binding Pattern)

  • 值绑定
let point = (2, 0)

switch point {
case (_, 0 ):
    print("1234000")
case let (_, y):
    print("33333333", y)
}

五、元组模式(Tuple Pattern)

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

六、枚举Case模式(Enumeration Case Pattern)

  • if case 语句等价于只有1个case的switch语句
var age = 2

// 原来的写法
if age >= 0 && age <= 9 {
    print("[0...9]")
}
// case模式,“=” 意思是匹配
if case 0...9 = age {
    print("[0...9]")
}

guard case 0...9 = age else { return }
print("[0...9]")
  • switch写法
switch age {
case 0...9: print("[0...9]")
default: break
}

// 元组的for case匹配
let points = [(1, 0), (2, 1),(3, 0)]
for case let (x, 0) in points {
    print(x)
} // 1, 3

七、可选模式(Optional Pattern)

  • 可选模式
let height: Int? = 10
if case .some(let x) = height {
    print("height1 = ", x)
}
if case let x? = height {
    print("height2 = ", x)
}
if let x = height {
    print("height3 = ", x)
}

let heights: [Int?] = [nil, 2, 3, nil, 5]
for case let x? in heights {
    print("x = ", x)
}
// 等价于上面的
for height in heights {
    if let x = height {
        print(x)
    }
}

八、类型转换模式(Type-Casting Pattern)

  • 类型转换
var num: Any = 2

switch num {
case is Int:
    // 编译器依然认为num是Any类型
    print("( is Int)", num)
    // 如果需要转Int、需要用下面的👇🏻
//case let n as Int:
//    print("as Int, \(n + 1)")
default:
    print("other")
}

九、表达式模式(Expression Pattern)

  • 表达式
let point = (2, 0)

switch point {
case (0, 0 ):
    print("(0,0) is at the origin)")
case (-2...2, -2...2):
    print("point.0 =", point.0, "point.1 =",point.1)
default:
    print("other")
}
  • 自定义模式一
struct Student {
    var score = 0, name = ""
    // 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: "JJJ")

switch stu {
case 100: print(">= 100")
case 90: print(">= 90")
case 80..<90: print("[80, 90]]")
case 60...79: print("[60, 79]]")
case 0: print(">= 0")
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 = "JJJ"
switch str {
case hasPrefix("j"), hasSuffix("J"):
    print("以j开头、以J结尾")
default:
    break
}
  • 自定义表达式三
// 偶数
func isEven(_ i: Int) -> Bool {
    i % 2 == 0
}

// 奇数
func isOdd(_ i: Int) -> Bool { i % 2 != 0 }

extension Int {
    // pattern: (Int) -> Bool,接收的是一个Int的value
    static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
        pattern(value)
    }
}

var age = 9

switch age {
// 匹配(Int) -> Bool 这样的表达式
case isEven:
    print("偶数")
case isOdd:
    print("奇数")
default:
    print("其他")
}

// 写法升级,
// 可以把 isEven、isOdd这样的写法换成 ~> 这样
// 自定义表达式
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 num = 0

switch num {
// 匹配(Int) -> Bool 这样的表达式
case ~<=10 where num>0:
    print("大于0,小于10")
case ~>10:
    print("大于10")
default:
    print("其他")
}

至此Swift的模式匹配基本涵盖,有不足之处还请各位大佬批准指正,不胜感激!!!

相关文章

  • ios 经典面试案例 (七)

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

  • 模式匹配

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

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

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

  • Swift-模式匹配

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

  • Swift 模式匹配总结

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

  • Swift中的模式匹配

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

  • swift模式匹配

    一、模式 1、什么是模式? 模式是用于匹配的规则,比如switch的case、捕捉错误的catch、if\gura...

  • Swift 模式匹配

    在 Swift 中,使用 ~= 来表示模式匹配的操作符。如果我们看看 API 的话,可以看到这个操作符有下面几种版...

  • swift 模式匹配

    写swift一时爽,一直写一直爽~~~ 模式匹配 switt中强大的switch case 结合枚举和元祖会有意想...

  • swift模式匹配

    模式 什么是模式? 模式是用于匹配的规则,比如switch的case、捕捉错误的catch、if\guard\wh...

网友评论

      本文标题:Swift基础知识之模式匹配

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