NOT condition in 'if case' statement

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

    There aren't any answers yet mentioning the guard statement, introduced by Swift 2, which is a neat addition to the tools above and, if you ask me, the cleanest solution if you can live with the requirement to return from your function or closure within the else-block:

    guard case .B = a else {
        // a does not match .B
        return
    }
    

    See Apple's "The Swift Programming Language (Swift 2.2): Statements" for more info.

提交回复
热议问题