Search code examples
swiftenumsenumeration

Can create enumeration as part of another enumeration?


I tried to create enum, which elements will be copied of another enum, like this:

enum Modes {
    case mode1
    case mode2
    case additionalMode1
    case additionalMode2
}

enum GeneralModes {
    case mode1
    case mode2
}

I have no idea how to do this. Need some backup. Thanks for all answers and ideas.


Solution

  • You can't make an enum inherit from another enum and there is no built-in way to make your enum implement all cases that another enum implemented.

    One possible workaround would be to give Modes a case with an associated value, which will be of type GeneralModes.

    enum Modes {
        case general(GeneralModes)
        case additionalMode1
        case additionalMode2
    }
    
    enum GeneralModes {
        case mode1
        case mode2
    }
    

    Then you can create a variable of type Modes with a value of mode1 like

    let mode1 = Modes.general(.mode1)