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 }
?
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 { ... }
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.
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.
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.