Comparing enums without their associated values


(Suyash Srijan) #1

It would be nice if you could compare an enum without its associated values i.e a case equality check only rather than case & associated value equality check.

For example:

enum Foo {
    case bar(Int, String)
}

let test: Foo = .bar(1, "Hello")

let isEqualWithItsAssocValues = test == .bar(1, "Hello") // true
let isEqualWithoutItsAssocValues = test == .bar(_, _) // also true

This makes it really easy to compare enums if you only care about the case and not its associated values and you wouldn't have to write your own equatable conformance, which could lead to problems if you want to compare with the associated values.

If the compiler could synthesise this or allow comparison without associated values then it would be helpful.

For example, a protocol like CaseEquatable perhaps?


(Jeremy David Giesbrecht) #2

In many places (if, guard, switch, etc.) you can already do this:

if case .bar = test {
    // ...
}

But it would be nice to have a shorter way of assigning the result or passing it to a function parameter, because this is tedious:

let isEqualWithoutItsAssocValues = { if case .bar = test { return true } else { return false } }()

The idea of synthesized properties of the form var isBar: Bool has also come up. That is another way of solving the same problem:

let isEqualWithoutItsAssocValues = test.isBar

#3

You could manually create a nested enum without associated values:

enum Foo {
  case bar(Int)
  case baz(String)
  
  var `case`: Case {
    switch self {
    case .bar: return .bar
    case .baz: return .baz
    }
  }
  
  enum Case {
    case bar
    case baz
  }
}

(Dante Broggi) #4

Linking an older thread on this topic.


(Charles Constant) #5

Yes, I use the "duplicate but payloadless enum thing" occasionally. It's ugly and verbose, but wow can it ever make life easier. Swift should give us a way to implement that code for us.