Swift 2 - Pattern matching in “if”

前端 未结 1 1933
时光取名叫无心
时光取名叫无心 2020-11-29 05:25

Recently I\'ve saw the WWDC 2015 keynote from Apple. I also looked at some documentation but I can\'t find a \"pattern matching in if\" section, how it was written on one of

相关标签:
1条回答
  • 2020-11-29 05:32

    All it really means is that if statements now support pattern matching like switch statements already have. For example, the following is now a valid way of using if/else if/else statements to "switch" over the cases of an enum.

    enum TestEnum {
        case One
        case Two
        case Three
    }
    
    let state = TestEnum.Three
    
    if case .One = state {
        print("1")
    } else if case .Two = state {
        print("2")
    } else {
        print("3")
    }
    

    And the following is now an acceptable way of checking if someInteger is within a given range.

    let someInteger = 42
    if case 0...100 = someInteger {
        // ...
    }
    

    Here are a couple more examples using the optional pattern from The Swift Programming Language

    let someOptional: Int? = 42
    // Match using an enumeration case pattern
    if case .Some(let x) = someOptional {
        print(x)
    }
    
    // Match using an optional pattern
    if case let x? = someOptional {
        print(x)
    }
    
    0 讨论(0)
提交回复
热议问题