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
switchstatement 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.
Unfortunately, like the enum example I talked about in the previous post, this conformance to
Equatableis 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
Equatableconformance 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
dumpfunction as a safeguard.
dumpis 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
dumpis 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
dumpoutputs are different.
Stay up-to-date by subscribing to the Comments RSS Feed for this post.