Equatable enums with associated values

Enums with associated values are a very powerful tool in Swift. You can store context sensitive information along with the value of the enum itself without the need of an additional data structure. But, as of in Swift 3.1, it has some serious limitations. For example, comparisons of enums are not that easy. Let’s look at this simple code:

That’s easy and it works as expected. But what happens, if we want to put some grade of happiness in the enum?

The compiler gives an error

Enums.playground:19:10: note: binary operator '==' cannot be synthesized for enums with associated values
if mood == Happiness2.Sad {

even though we did not compare our value with the enum member with the associated value. „Too bad, so sad“, as Donald Trump would say. The only possibility to compare those enums is via the switch construction. But wait, that we can put in the enum itself. We can make the enum „equatable“. Here is the solution:

Now everything’s fine. I admit, the comparison function in the enum is quite lengthy and ugly and its getting worse, the more members you have in the enum. But this is the only way I know of, to keep your logic code clean and simple. Now you can even write something like this:

OK, you can get it shorter by using Swift’s ability of the switch construct to act on tuples as stated in some other blogs (e.g. by Ole Begemann). Instead of nested switch statements we can test on both sides in one switch:

We use the “_” for those terms we are not interested in (in the sense of „any“). We did not use a default case on purpose. With a default case we would not get warned if we would extend the enum with more members without the extension of the switch statement.

Somehow it’s a matter of taste which version you prefer. The second one is a little bit shorter but maybe harder to read.

Here is the playground for this simple example:


Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.