美文网首页
第三十四章 Swift 模式匹配

第三十四章 Swift 模式匹配

作者: 我有小尾巴快看 | 来源:发表于2019-06-12 11:08 被阅读0次

Swift提供的模式匹配对Switch进行了扩充,我们可以使用if...elseguard let来简化代码。

// 这里定义枚举水果,有苹果和香蕉
// 香蕉有一个入参,代表染色体倍数
enum Fruit {
    case apple
    case banana(value: UInt)
}

你会发现相关值并不能直接进行比较,因为与之一起的参数是不可控的。

let fruit = Fruit.apple

if fruit == Fruit.apple { // Binary operator '==' cannot be applied to two 'Fruit' operands
    
}

所以我们只能通过模式匹配的方式在进行匹配。

let fruit = Fruit.banana(value: 3)

if case let .banana(value) = fruit {
    print(value) // 3
}

其实模式匹配是以Swich原型的,你可以像if...elseif...else语法一样使用它。

let fruit = Fruit.banana(value: 3)

if case let .banana(value) = fruit {
    print(value) // 3
} else if case let .apple = fruit {
    print("apple")
} else {
    print("unknow")
}

switch fruit {
case let .apple:
    print("apple")
case let .banana(value):
    print(value)
}


如同SQL中的where用来添加限制条件:select * from table where age > 18,Swift可以在条件语句中添加where来增加条件

let a: Int? = 3
if let b = a where b > 5 { // Expected ',' joining parts of a multi-clause condition

}

不过现版本中条件语句已经不允许这么使用了,编译器会提示你where应该替换为逗号,

let a: Int? = 3
if let b = a, b > 5 { 
        
}

但你仍然可以在扩展中使用where,我们在这里给Int类型的Range添加一个函数。

extension Range where Bound == Int {
    func log() {
        print(upperBound,lowerBound)
    }
}

相关文章

  • 第三十四章 Swift 模式匹配

    Swift提供的模式匹配对Switch进行了扩充,我们可以使用if...else或guard let来简化代码。 ...

  • 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/ucekfctx.html