swiftenumsswitch-statementoption-typeassociated-value

How to declare an `enum` of `enum` that allows for "flattened" `switch` statement?


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?


Solution

  • You could do this with …

    switch b {
    case .nope: // stuff
    case .dope(.yep): // other stuff
    case .dope(.someOtherCase): // more stuff
    }
    

    Responding to your comment…

    Imagine you could flatten it like you said. How would you deal with…

    enum Foo {
        case a
        case b(Bar)
        case c(Bar)
    }
    

    If you are allowed to exclude the .b from the switch then there is no way to differentiate between .b and .c.