I would like to test the equivalency of a couple variables of enumeration types, like this:
enum AnEnumeration {
case aSimpleCase
case anotherSimpleCase
case aMoreComplexCase(String)
}
let a1 = AnEnumeration.aSimpleCase
let b1 = AnEnumeration.aSimpleCase
a1 == b1 // Should be true.
let a2 = AnEnumeration.aSimpleCase
let b2 = AnEnumeration.anotherSimpleCase
a2 == b2 // Should be false.
let a3 = AnEnumeration.aMoreComplexCase("Hello")
let b3 = AnEnumeration.aMoreComplexCase("Hello")
a3 == b3 // Should be true.
let a4 = AnEnumeration.aMoreComplexCase("Hello")
let b4 = AnEnumeration.aMoreComplexCase("World")
a3 == b3 // Should be false.
Sadly, these all produce this errors like this one:
error: MyPlayground.playground:7:4: error: binary operator '==' cannot be applied to two 'AnEnumeration' operands
a1 == b1 // Should be true.
~~ ^ ~~
MyPlayground.playground:7:4: note: binary operator '==' cannot be synthesized for enums with associated values
a1 == b1 // Should be true.
~~ ^ ~~
Translation: If your enumeration uses associated values, you can't test it for equivalency.
Note: If .aMoreComplexCase
(and the corresponding tests) were removed, then the code would work as expected.
It looks like in the past people have decided to use operator overloading to get around this: How to test equality of Swift enums with associated values. But now that we have Swift 4, I wonder if there is a better way? Or if there have been changes that make the linked solution invalid?
Thanks!