Matthieu Riegler Matthieu Riegler - 5 months ago 15
Swift Question

Compare Swift enum regardless of the associated value

Is it somehow possible to test an enum case regardless of the associated value ?

enum Abc {
case A(a:Int)
case B(b:Int)
}

let a = Abc.A(a:1)

a == Abc.A // <= Not possible

Answer

Sure, you can do this in a switch:

switch a {
case .A:
    print("it's A")
default:
    print("it's not A")
}

Or use pattern matching in an if statement:

if case .A = a {
    print("it's A")
} else {
    print("it's not A")
}

If you're still interested in the associated value after matching the case, you can extract it like so:

switch a {
case .A(let value):
    ...
}

if case .A(let value) = a {
    ...
}

Note @overactor's comment below that you can also write this as case let .A(value) – it's really a matter of personal preference.