美文网首页Swift编程
总结swift中模式匹配的用法

总结swift中模式匹配的用法

作者: fuadam1982 | 来源:发表于2019-08-14 01:04 被阅读0次

看了一些介绍pattern matching的文章,里面有不少种使用用法。总结下来就是两种类型:绑定和判断。模式匹配的起手式是case,这是对传统switch-case的扩展。具体用法如下:

  1. 「绑定」即let,它表示匹配的数据绑定到变量上。形式是case let (aVar)或case (let aVar)
    a. 对变量可以添加where约束条件
    b. _ 可以匹配任意数据,但是无法使用
    c. case let aVar? 用于匹配可选类型的.some值
    d. case let .some(aVar) 用于匹配枚举中的一个枚举值
  2. 「判断」相当于 ==,它只有true/false结果没有绑定的变量
    a. 一种方式是 case is aType
    b. 一种方式是case (aVar...bVar) = value,相当于range的contains方法
  3. ~= 是模式匹配操作符可以通过重载实现自定义模式匹配。系统库提供了range的~=匹配实现

下面是测试用例:

/** 测试数据 */
private let arr = [(1, 1), (2, 4), nil, (1, 3), nil, (2, 2)]

private func optionalMatch() {
    for case let item? in arr {
        print("optionalMatch: \(item)")
    }
}

private func ifMatch() {
    for (idx, item) in arr.enumerated() {
        // if nil = item
        if case let .none = item {
            print("ifMatch-optional nil at \(idx)")
        } else if case let (1, item)? = item {
            print("ifMatch-enum item \(item)")
        }
    }
}

private func tupleMatch() {
    for case let (2, item)? in arr {
        if case (_, 2) = (2, item) {
            print("tupleMatch-case: \(item)")
        } else {
            print("tupleMatch-for: \(item)")
        }
    }
}

private func whereMatch() {
    for case let (a, b)? in arr where a == 1 && b > 1 {
        print("whereMatch where 1: \(b)")
    }
}

private func rangeMatch() {
    for case let item? in arr {
        if case (2..<3, 3...4) = item {
            print("rangeMatch-case, \(item)")
        } else if (3...5) ~= item.1 {
            // if (3...5).contains(item.)
            print("rangeMatch ~=, \(item)")
        }
    }
}

private func switchMatch() {
    for item in arr {
        switch item {
        case nil:
            print("switchMatch nil")
        case let (2, b)?:
            let subA: Any = b
            switch subA {
            case let b as Int where b == 4:
                print("switchMatch as Type \(item)")
            case is Int:
                print("switchMatch is Type \(item)")
            default:
                continue
            }
        default:
            print("switchMatch default \(item)")
        }
    }
}

/** 自定义匹配方法 */
func ~= (pattern: String, value: Int) -> Bool {
    return pattern == "\(value)"
}

private func customMatch() {
    for item in arr.compactMap({$0}) {
        switch item {
        case ("1", "3"):
            print("customMatch \(item)")
        default:
            continue
        }
    }
}

private let printResult: (() -> ()) -> () = { action in
    print()
    action()
    print()
    print("==============================")
}

/** 入口方法 */
func runMatchPatternsDemo() {
    printResult(optionalMatch)
    printResult(ifMatch)
    printResult(tupleMatch)
    printResult(whereMatch)
    printResult(rangeMatch)
    printResult(switchMatch)
    printResult(customMatch)
}

运行结果如下:

optionalMatch: (1, 1)
optionalMatch: (2, 4)
optionalMatch: (1, 3)
optionalMatch: (2, 2)

==============================

ifMatch-enum item 1
ifMatch-optional nil at 2
ifMatch-enum item 3
ifMatch-optional nil at 4

==============================

tupleMatch-for: 4
tupleMatch-case: 2

==============================

whereMatch where 1: 3

==============================

rangeMatch-case, (2, 4)
rangeMatch ~=, (1, 3)

==============================

switchMatch default Optional((1, 1))
switchMatch as Type Optional((2, 4))
switchMatch nil
switchMatch default Optional((1, 3))
switchMatch nil
switchMatch is Type Optional((2, 2))

==============================

customMatch (1, 3)

==============================

相关文章

  • Swift 模式匹配总结

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

  • 总结swift中模式匹配的用法

    看了一些介绍pattern matching的文章,里面有不少种使用用法。总结下来就是两种类型:绑定和判断。模式匹...

  • ios 经典面试案例 (七)

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

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

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

  • Swift-模式匹配

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

  • Swift中的模式匹配

    1、模式匹配2、where和模式匹配 1、模式匹配 虽然在Swift中没有内置的正则表达式支持,但是一个和正则表达...

  • Swift中的模式匹配

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

  • Swift中的模式匹配

    Swift里的switch比OC里面强大很多,switch的主要特性就是模式匹配。下面先举个非常简单的例子。 看完...

  • Swift中强大的模式匹配

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

  • bash的if语句用法之:模式匹配

    bash的if语句用法之:模式匹配 基本语法: 注意有两点: 模式匹配操作符号: =~ 用双中括号 [[和]]括起...

网友评论

    本文标题:总结swift中模式匹配的用法

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