[swift-users] Making Error sub-enums Equatable
Brent Royal-Gordon
brent at architechies.com
Wed May 10 03:23:21 CDT 2017
> On May 8, 2017, at 2:01 AM, Rick Mann via swift-users <swift-users at swift.org> wrote:
>
> Seriously, I've been googling this for a half-hour, and I can't find an answer (everything that comes up is for ErrorType, absolutely nothing for Error).
>
> I have an enum:
>
> enum MyErrors : Error
> {
> case one(String)
> case two
> case three(String)
> }
>
> let a: MyErrors = .one("foo")
> let b = .two
> let c = .towo
>
> I want to compare them with ==, and I don't care about the associated types. I can't for the life of me figure out how without an exhaustive switch statement in a == definition. Is that the only way?
Yes, the correct way to compare two enums is with a `switch` statement.
The good news is, Swift's `switch` statement is good enough that these aren't terribly difficult to write. My preferred pattern (given your "ignore the associated type" semantic) is:
extension MyErrors: Equatable {
static func == (lhs: MyErrors, rhs: MyErrors) -> Bool {
switch (lhs, rhs) {
case (.one, .one):
return true
case (.two, .two):
return true
case (.three, .three):
return true
case (.one, _), (.two, _), (.three, _):
return false
}
}
}
You do it this way instead of using `default:` so that, if you add another case later, it won't just get matched by the `default:` and always return `false`.
(P.S. I would suggest using a name like `MyError`, not `MyErrors`. A given instance of `MyError` only represents one of the errors, not several of them.)
--
Brent Royal-Gordon
Architechies
More information about the swift-users
mailing list