== operator for enums with (ignored) associated values

Hi, enums already have support for "==" operation, which is great for doing things like

let goingNorth = (direction == .north)

But as soon as you add a value to the enum, you can't create expressions anymore, which is a pity (because let x = case .north(_) = direction is not a thing yet).

Would it be possible to add syntactic sugar to let people write

let goingNorth = (direction == .north( _ ) )

Instead of

var goingNorth = false
if case .north(_) = direction { goingNorth = true }
?

2 Likes

There has been some discussion in the past about making this more ergonomic. I believe the current recommended practice is to manually define a nested enum without associated values like so:

enum Foo {
  case x(Int)
  case y(Double)
  case z

  enum Case { case x, y, z }

  var `case`: Case {
    switch self {
    case .x: return .x
    case .y: return .y
    case .z: return .z
    }
  }
}

Which then allows you to write things like:

let a = Foo.x(3)
let b = a.case == .y
if a.case == .z { ... }
6 Likes

The tricky thing is that you may or may not want to ignore the associated values, depending on the individual use case. Since "equality" can therefore have different meanings, I'm tempted to say we should use different operators (something like ~==) to be explicit about what kind of equality we're talking about.

1 Like

I understand you concern, but i don't think

x == .case1(_)

is ambiguous, if you look at the expression as a whole, since you specifically indicated (_).
I do agree that it only works for comparing with enum litterals, and not between any variable of an enum type. That's why my proposal is to add syntactic sugar, and not a general automatic implementation of "==" for any enum with associated value.

1 Like

Whatever the operator, I would really like to see support for pattern matches as arbitrary boolean expressions (at least when the pattern match doesn’t include any variable bindings). if case remains a nasty snag in the language.

2 Likes

I think a better approach would be to have compiler generated computed properties that to the checks for us.

let goingNorth = direction.isNorth

I think this has been pitched in the past, but more recently the guys at pointfree.co have been talking about this in their recent episodes.

It would solve a pretty common use case.

2 Likes
Terms of Service

Privacy Policy

Cookie Policy