I wanted to circle back to this comment from @Joe_Groff:
Has there been any recent discussion about this? I'd love for enums to be a bit more ergonomic via optional-chaining. Key path support would be a nice, free bonus! I can imagine it working simply for cases with a single associated value:
enum Result<Value, Other> {
case value(Value)
case other(Other)
}
let result: Result<Int, String> = .value(1)
result.value // Int?.some(1)
result.other // nil
Cases with multiple associated values could return tuples:
enum Color {
case rgba(red: Float, green: Float, blue: Float, alpha: Float)
…
}
let color = Color.rgba(red: 1, green: 0, blue: 0, alpha: 1)
color.rgba // (red: Float, green: Float, blue: Float, alpha: Float)?.some(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
color.rgba?.red // Float?.some(1.0)
color.rgba?.0 // Float?.some(1.0)
So how about cases with no associated values? Do they return Optional<Void>
?
enum TrafficLight {
case green
case yellow
case red
}
let trafficLight = TrafficLight.green
trafficLight.green // TrafficLight?.some(())
trafficLight.yellow // nil
Probably not? How about returning Bool
instead?
if trafficLight.green {
// …
}
This is better, but we probably want to prefix with is
and camelcase the accessor.
trafficLight.isGreen // true
trafficLight.isYellow // false
While we're at it, why not derive these boolean accessors everywhere?
result.isValue // true
result.isOther // false
color.isRgba // true
Edit: Here's a link to a draft!