Optional in Swift allows for magic where switch-ing over an optional enum flattens the cases into a single switch statement.
Given:
enum Foo {
case bar, baz
}
You can:
let foo: Foo? = .bar
switch foo {
case .bar:
break
case .baz:
break
case nil:
break
Here, Optional is an enum and Foo is an enum, but just one single statement is enough to cover all cases of both.
Question: can I declare my own enum inside another enum so that the cases can be handled in a flat way too?
So that I could:
enum Foo<Bar> {
case nope
case dope(Bar)
}
enum Baz {
case yep
}
let b: Foo<Baz> = .dope(.yep)
switch b {
case .nope:
break
case .yep:
break
}
Maybe if I call the case Foo.dope as Foo.some? Maybe there is an annotation that I can use?
You could do this with …
Responding to your comment…
Imagine you could flatten it like you said. How would you deal with…
If you are allowed to exclude the
.bfrom the switch then there is no way to differentiate between.band.c.