Reputation: 55856
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
Upvotes: 4
Views: 689
Reputation: 80951
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 mainly a matter of personal preference.
Upvotes: 4
Reputation: 1789
You can use an if case
enum ABC {
case A(a: Int)
case B(b: Int)
}
let a = ABC.A(a: 1)
if case .A = a {
...
}
Upvotes: 1