Been thinking this through, and maybe the better way to think about this would be a "Common Associated Value" rather than a "Stored Property". The goal is to easily access a value that's included in every case, not to extend/add anything per-se.
I'm sure it's been referenced in previous discussion, but Kotlin's sealed class supports this kind of thing (With the caveat that Swift's enum varies in many ways):
sealed class MyClass(val myValue: String) {
class SubType(val title: String): MyClass("Test")
class OtherType(val order: Integer, myValue: String): MyClass(myValue)
}
val instance: MyClass = MyClass.Subtype("It works!")
// Since `myValue` is part of `MyClass` it can be accessed without determining the subclass
val value = instance.value
It seems like the more Swifty approach would be code generation to support the convenience. (Forgive me if this has been discussed/proposed already)
e.g. given your enum...
enum Color {
case rgb(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat)
case white(white: CGFloat, alpha: CGFloat)
case hsl(hue: CGFloat, saturation: CGFloat, luminosity: CGFloat, alpha: CGFloat)
var alpha: CGFloat
}
/// Full generated version
enum Color {
case rgb(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat)
case white(white: CGFloat, alpha: CGFloat)
case hsl(hue: CGFloat, saturation: CGFloat, luminosity: CGFloat, alpha: CGFloat)
var alpha: CGFloat {
get {
switch self {
case let .rgb(_, _, _, a): return a
case let .white(_, a): return a
case let .hsl(_, _, _, a): return a
}
}
}
}
If needed it could be opt-in with a protocol, but I haven't come up with a reasonable name/functionality that makes sense. GeneratedCommonValues is explicit, but doesn't really seem to fit in with other protocols with generation.
Side-note, not sure if set would/should be generated since IMO it "feels" wrong to have in enums by default, but it could also easily be added in separately.