Is there a way to write an `if case` statement as an expression?

后端 未结 3 625
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 17:13

Consider this code:

enum Type {
    case Foo(Int)
    case Bar(Int)

    var isBar: Bool {
        if case .Bar = self {
            return true
        } else {         


        
3条回答
  •  醉梦人生
    2021-02-01 17:24

    I have a similar wondering, and I kept searching for some work arounds about this, and landed on this page. I came up with code like this to compromise.

    fileprivate enum TypePrimitive {
        case foo
        case bar
    }
    
    enum Type {
        case foo(Int)
        case bar(Int)
        fileprivate var primitiveType: TypePrimitive {
            switch self {
            case .foo(_): return .foo
            case .bar(_): return .bar
            }
        }
        var isFoo: Bool { self.primitiveType == .foo }
        var isBar: Bool { self.primitiveType == .bar }
    }
    

    I hope Apple will provide better solution by adding some features in Swift language.

提交回复
热议问题