Friday, March 10, 2017 [Tweets] [Favorites]

Making Swift Enums and Structs Equatable

Ole Begemann:

The downside of not having a default case is, of course, more boilerplate to write. […] This isnʼt fun to write, and it would get even worse with more cases. The number of states the switch statement must distinguish grows quadratically with the number of cases in the enum.

[…]

You can make this considerably more manageable with some intelligent application of the _ placeholder pattern. While we saw above that a single default clause is not enough, one pattern per case is.

Ole Begemann:

Unfortunately, like the enum example I talked about in the previous post, this conformance to Equatable is very fragile: every time you add a property to the struct, you have to remember to also update the implementation of the == function. If you forget, your Equatable conformance will be broken, and depending on how good your tests are this bug has the potential to go undetected for a long time — the compiler wonʼt be able to help you here.

[…]

It occurred to me to use the standard libraryʼs dump function as a safeguard. dump is interesting because it uses Swiftʼs reflection capabilities to create a string representation of a value or object that includes all storage fields.

[…]

The biggest drawback of the solution might be that dump is not a perfectly reliable way to determine equality. It should be pretty good at avoiding false negatives, but youʼll probably see some false positives, i.e. values that really are equal but whose dump outputs are different.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment