Comparing enums without their associated values

I have a more radical stance on this: I believe associated values currently break enums in Swift.

Enums should be about comparing cases; looking up associated values goes one step beyond.

For instance, I use an enum like this in my code:

enum Marsupial {
    case koala
    case kangaroo
    case wombat
    case other
}

So in addition to switch blocks, my code is full of lines checking for individual cases like this:

if theAnimal == .koala {...

Suppose I want to add the possibility to store the name in the "other" case:

enum Marsupial {
    case koala
    case kangaroo
    case wombat
    case other (name: String?)
}

Suddenly, my enum is broken. Equality comparisons are out of the window, and I have to use some of the least intuitive syntax I've ever seen in Swift:

if case .kangaroo = theAnimal {

I now have to play with the Equatable protocol to at least match the cases other than other, and/or come up with computed properties of the enum like isKangaroo and isOther… While I would actually still expect the following to work:

if theAnimal == .kangaroo || theAnimal == .other { ...

Enums are about comparing cases. If we also want to look into associated values, let's use the let syntax:

if case let .other(animalName) = theAnimal, case let .other(beastName) = theBeast, animalName == beastName { ...

This may be complex, but IMO it is more appropriate to be complex than comparisons ignoring associated values, which should be simple, remaining true to the nature of an enum.

7 Likes