Check enum for equality in for ... where clause
How can I check for equality of an enum when it case
has an associated value? Contrived example:
enum Status : Equatable {
case success
case failed(error: String)
static func == (lhs: Status, rhs: Status) -> Bool {
switch (lhs, rhs) {
case (.success, .success), (.failed, .failed):
return true
default:
return false
}
}
}
let statuses = [
Status.success,
.failed(error: "error 1"),
.failed(error: "error 2"),
.success
]
// Failed: Binary operator '==' cannot be applied to operands of type 'Status' and '_'
for s in statuses where s == .failed {
print(s)
}
(I know I can test s != .success
, but the actual enum has more cases, so this is a hassle)
source to share
You can use if case
:
for status in statuses {
if case .failed = status {
...
}
}
But unfortunately you cannot use case
with a where
loop clause for
.
In this case, since you defined .failed
as equal to another, no matter what is related error
, you could theoretically do:
for status in statuses where status == .failed(error: "") {
show("\(status)")
}
I'm not crazy about this pattern because (a) it depends on the values ββbeing .failed
equal even though they have different meanings error
; and (b) it makes the code easy to misunderstand.
source to share