NOT condition in 'if case' statement

后端 未结 5 556
醉话见心
醉话见心 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:38

    I saw the guard answer, and I though I could improve upon it.

    Note how the do block is named. I mean, it works

    i: do { guard case .B = a else {
        print("foo")
    break i }}
    

    Granted, this is much smaller: if case .B = a {} else { *** }


    You can use this if you really want that ! operator

    func cases(_ a: T,_ b: T) -> Bool { return a == b }
    if cases(.B, a) {}
    if !cases(.B, a) {}
    

提交回复
热议问题