美文网首页
第三十四章 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 模式匹配

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