NOT condition in 'if case' statement

后端 未结 5 555
醉话见心
醉话见心 2021-01-01 09:04

I have an enum:

enum E {
    case A, B, C(Int)
}

let a: E = .A

Here\'s how I would check if a equals .B

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 09:31

    This "answer" is nothing more than writing your awkward solution in a more compact manner. If you only care about the case when a value is not of a certain enum value, you could write it like this all in one line with the else immediately following the empty then clause:

    enum E {
        case A, B(String), C(Int)
    }
    
    let a: E = .B("Hello")
    
    if case .A = a {} else {
        print("not an A")
    }
    
    if case .B = a {} else {
        print("not a B")
    }
    
    if case .C = a {} else {
        print("not a C")
    }
    

提交回复
热议问题