How do you use a switch statement with a nested enum?

后端 未结 4 876
你的背包
你的背包 2021-01-31 10:32

I\'ve created an enum for Instagram endpoints with nested enums similar to Moya.

enum Instagram {
    enum Media {
        case Popular
        case Shortcode(id         


        
4条回答
  •  时光取名叫无心
    2021-01-31 10:55

    I'm adding a more general answer for a few reasons.

    1. This is the only open question regarding nested enums and switch statements. The other one is sadly closed.
    2. The only legit answer does not show how to assign the value of a nested enum to a symbol. The syntax was not intuitive to me.
    3. None of the other answers have extensive case examples.
    4. An enum nested 3 levels deep is more illustrative of the required syntax. Using efremidze answer still took me a while to work it out.
    
    enum Action {
        case fighter(F)
        case weapon(W)
    
        enum F {
            case attack(A)
            case defend(D)
            case hurt(H)
    
            enum A {
                case fail
                case success
            }
            enum D {
                case fail
                case success
            }
            enum H {
                case none
                case some
            }
        }
        enum W {
            case swing
            case back
        }
    }
    
    // Matches "3 deep"
    let action = Action.fighter(.attack(.fail))
    // Matches "1 deep" because more general case listed first.
    let action2 = Action.weapon(.swing)
    
    switch action {
    case .fighter(.attack(.fail)):
        print("3 deep")
    case .weapon:
        print("1 deep")
    case .weapon(.swing):
        print("2 deep to case")
    case .fighter(.attack):
        print("2 deep to another enum level")
    default:
        print("WTF enum")
    }
    

提交回复
热议问题