代码之家  ›  专栏  ›  技术社区  ›  nambatee

关联值为另一个枚举的关联值的枚举(嵌套关联值)

  •  0
  • nambatee  · 技术社区  · 6 年前

    我有枚举 Foo 具有关联值。枚举 用作另一个枚举的关联值, Car . 我想知道如何访问 ,如下例所示:

    enum Foo: Equatable {
        case moo
        case zoo(String)
    }
    
    enum Car {
         case mar
         case dar(Foo)
         case gar(Foo)
    }
    
    func request(with type: Car) -> String {
         switch type {
         case .mar:
             return "mar"
         case .dar(let foo) where foo == .moo:
             return "darmoo"
         case .dar(let foo) where foo == .zoo(let value):
         // how can I access the associated value of foo?
         // This where syntax results in an error - Consecutive statements on a line must be separated by ';'
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   matt    6 年前

    func request(with type: Car) -> String {
        switch type {
        case .mar:
            return "mar"
        case .dar(let foo):
            switch foo {
            case .moo: return "darmoo"
            case .zoo(let s): return s
            }
        case .gar:
            return "gar"
        }
    }
    
        2
  •  3
  •   Cristik    6 年前

    可以使用模式匹配:

    switch type {
    case .mar:
        return "mar"
    case .dar(let foo) where foo == .moo:
        return "darmoo"
    case .dar(.moo):
        return "dar: moo"
    case let .dar(.zoo(value)):
        return "dar: \(value)"
    case .gar:
        return "gar"
    }
    

    或者,如果你想处理 Foo 以同样的方式 dar gar ,可以绑定 foo 在一种情况下:

    switch type {
    case .mar:
        return "mar"
    case .dar(let foo) where foo == .moo:
        return "darmoo"
    case let .dar(foo), let .gar(foo):
        switch foo {
        case .moo:
            return "moo"
        case let .zoo(value):
            return value
        }
    }