Swift: testing against optional value in switch case

前端 未结 3 1101
面向向阳花
面向向阳花 2020-12-07 23:45

In Swift, how can I write a case in a switch statement that tests the value being switched against the contents of an optional, skipping over the case if the option

3条回答
  •  -上瘾入骨i
    2020-12-08 00:20

    Optional is just a enum like this:

    enum Optional : Reflectable, NilLiteralConvertible {
        case none
        case some(T)
    
        // ...
    }
    

    So you can match them as usual "Associated Values" matching patterns:

    let someValue = 5
    let someOptional: Int? = nil
    
    switch someOptional {
    case .some(someValue):
        println("the value is \(someValue)")
    case .some(let val):
        println("the value is \(val)")
    default:
        println("nil")
    }
    

    If you want match from someValue, using guard expression:

    switch someValue {
    case let val where val == someOptional:
        println(someValue)
    default:
        break
    }
    

    And for Swift > 2.0

    switch someValue {
    case let val where val == someOptional:
        print("matched")
    default:
        print("didn't match; default")        
    }
    

提交回复
热议问题