5

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!

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
MadEmperorYuri
  • 298
  • 3
  • 11
  • 3
    Those answers are still valid. It will become simpler when https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md is implemented. – Martin R Oct 17 '17 at 04:02
  • That's what I needed. I've got my code now working properly. Perhaps you should make this comment be an answer, so I can mark this as resolved? – MadEmperorYuri Oct 17 '17 at 04:23

1 Answers1

6

The Swift proposal

has been accepted and implemented in Swift 4.1 (Xcode 9.3):

... synthesize conformance to Equatable/Hashable if all of its members are Equatable/Hashable.

therefore it suffices to

... opt-in to automatic synthesis by declaring their type as Equatable or Hashable without implementing any of their requirements.

In your example – since String is Equatable – it will suffice to declare

enum AnEnumeration: Equatable {
  case aSimpleCase
  case anotherSimpleCase
  case aMoreComplexCase(String)
}

and the compiler will synthesize a suitable == operator.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    Any idea why this would be *opt-in*, not opt-out? – LinusGeffarth Jun 06 '18 at 08:02
  • 1
    @LinusGeffarth: It is explained at https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md#requesting-synthesis-is-opt-in . – Martin R Jun 06 '18 at 09:36