问题
How can I test for enum equality when a case has an associated value? A 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 for s != .success but the actual enum has more cases so they are a hassle)
回答1:
You can use if case:
for status in statuses {
if case .failed = status {
...
}
}
But, unfortunately, you can't use case with the where clause of for loop.
In this case, though, because you've defined .failed to be equal to another regardless of what the error associated value was, you theoretically could do:
for status in statuses where status == .failed(error: "") {
show("\(status)")
}
I'm not crazy about that pattern because (a) it's contingent upon the fact that .failed values are equal even if they have different error associated values; and (b) it results in code that is easily misunderstood.
来源:https://stackoverflow.com/questions/44099325/test-enum-for-equality-in-for-where-clause