Swift: testing against optional value in switch case

前端 未结 3 1108
面向向阳花
面向向阳花 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条回答
  •  心在旅途
    2020-12-08 00:16

    In Swift 4 you can use Optional : ExpressibleByNilLiteral of Apple to wrappe optional

    https://developer.apple.com/documentation/swift/optional

    Example

    enum MyEnum {
        case normal
        case cool
    }
    

    some

    let myOptional: MyEnum? = MyEnum.normal
    
    switch smyOptional {
        case .some(.normal): 
        // Found .normal enum
        break
    
        case .none: 
        break
    
        default:
        break
    }
    

    none

    let myOptional: MyEnum? = nil
    
    switch smyOptional {
        case .some(.normal): 
        break
    
        case .none: 
        // Found nil
        break
    
        default:
        break
    }
    

    default

    let myOptional: MyEnum? = MyEnum.cool
    
    switch smyOptional {
        case .some(.normal): 
        break
    
        case .none: 
        break
    
        default:
        // Found .Cool enum
        break
    }
    

    Enum with value

    enum MyEnum {
        case normal(myValue: String)
        case cool
    }
    

    some value

    let myOptional: MyEnum? = MyEnum.normal("BlaBla")
    
    switch smyOptional {
    case .some(.normal(let myValue)) where myValue == "BlaBla":
        // Here because where find in my myValue "BlaBla"
        break
    
    // Example for get value
    case .some(.normal(let myValue)):
        break
    
    // Example for just know if is normal case enum
    case .some(.normal):
        break
    
    case .none:
        break
    
    default:
    
        break
    }
    

提交回复
热议问题