swiftenumsboolean-logicassociated-value

Use "or" logic with multiple "if case" statements


Suppose I have an enum case with an associated value, and two variables of that enum type:

enum MyEnum {
    case foo, bar(_ prop: Int)
}

let var1 = MyEnum.foo
let var2 = MyEnum.bar(1)

If I want to check if both variables match the general case with the associated value, I can do that with a comma:

if case .bar = var1, case .bar = var2 {
    print("both are bar")
}

But I need to check if either matches the case, with something like this:

if case .bar = var1 || case .bar = var2 {
    print("at least one is bar")
}

However, that doesn't compile. Is there another way to write this to make the logic work?


Solution

  • I would resort to some sort of isBar property on the enum itself, so that the "a or b" test remains readable:

    enum MyEnum {
        case foo, bar(_ prop: Int)
    
        var isBar: Bool {
            switch self {
            case .bar: return true
            default: return false
            }
        }
    }
    
    let var1 = MyEnum.foo
    let var2 = MyEnum.bar(1)
    
    let eitherIsBar = var1.isBar || var2.isBar