Swift: Comparing Enums With Associated Values

comparing enums with associated values

Comparing enums in Swift is very straightforward – as long as they don’t have associated values. In this post we will discuss, what you can do in that case.

Hint: This post is using Swift 4

Content

Video


Comparing Enums Without Associated Values

Let’s start with the simple case:

So in this example we are defining an enum called TestEnum, that has two cases. Then we are declaring two variables of this type and we compare them – they behave as expected and everything is working fine.

Comparing Enums With Associated Values

Now let’s look into the hard stuff. First, we add an associated value to one of the cases:

As already explained in this post, you can use an enum with associated values to add some additional information. It can only be accessed within a switch statement though:

As expected, the output is

So, now let’s try to compare two of them:

In this case, we get an compiler error:

And this makes perfectly sense because it’s not clear when they are equal. For example, are two testA values equal if their associated values are equal? Or are two testA values always equal? It depends on the circumstances, on the meaning of the enum.

But we can actually implement our own implementation of ==. For that, we implement the Equatable protocol:

That’s a lot of code for a little bit of work, but it does the job! Now, two TestEnum are equal, if one of the following two conditions is true:

  • Both are testB cases.
  • Both are testA cases AND their associated values are equal.

Of course it’s possible to write that code a little bit more elegant:

And now let’s test whether it’s working as expected:

Obviously, it can also be implemented in another way, like this:

  • Both are testB cases.
  • Both are testA cases

Then, the associated values don’t have an influence on the equality:

As said before, it depends on the context.

Title Image: @ arda savasciogullari / shutterstock.com