[swift-users] Making Error sub-enums Equatable

Rick Mann rmann at latencyzero.com
Wed May 10 04:05:44 CDT 2017


> On May 10, 2017, at 01:23 , Brent Royal-Gordon <brent at architechies.com> wrote:
> 
>> 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`.

This seems so obvious that I feel like it should be provided by the language by default. I suppose you can make it even more compact with

    case (.one, .one),
         (.two, .two),
         (.three, .three):
	return true

Maybe swift could provide a 'case==()' so one needn't write this (I can see it getting quite tedious and error-prone, should one forget to update the equality after adding additional cases).

> (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.)

I did in my actual code. This was just quickly typing the email and hiding the real error name.


-- 
Rick Mann
rmann at latencyzero.com




More information about the swift-users mailing list