Since I started using Swift, I've been drawn to enums
for their features (associated values, type safety, etc.)
However, I noticed that in doing so, I lost some polymorphism. Consider the traffic light enum:
enum TrafficLight {
case green
case yellow
case red
}
Let's say I want to add a canAdvance
function, I'll end up with something like this (discussing if advancing in yellow is fine is out of the scope ;) )
enum TrafficLight {
case green
case yellow
case red
func canAdvance() -> Bool {
switch self {
case .green:
return true
case .yellow, .red:
return false
}
}
}
This works, but if your enum grows and needs more methods, we end up with a switch within each method.
What I'd love to see is a way to remove those switches, that can enable tidier code. I'm thinking on something like this:
enum TrafficLight {
case green
case yellow
case red
func canAdvance() -> Bool {
return false
}
}
extension TrafficLight where case .green {
func canAdvance() -> Bool {
return true
}
}
This would enable extensions on enums for each different case.
I don't know if this is easy (or even possible) to implement, plus, this is my first time writing on the forum, so any comments are welcome.