测试枚举集的相互成员资格的最佳方法

时间:2017-05-07 04:02:29

标签: swift enums nsset

有没有一种很好的方法可以将不同的枚举分组到集合中来测试相互成员身份,而不需要大量的代码重复?

例如,下面,当我得到.coldBeverage时,我得到[.cola, .milk, .wine],同样如果我得到.cola.milk.wine我得到.coldBeverage

enum BeverageType {
     case coldBeverage
     case hotBeverage
}

enum Beverage {
    case cola 
    case milk 
    case wine 
    case coffee 
    case tea 
    case hotChocolate 
}

当然,我总是可以在每个枚举上创建一个var,并输入每种类型的倒数关系。只是好奇是否有其他结构。

extension BeverageType {
    var associatedBeverages: [Beverage] {
         switch self {
            case .coldBeverage:
                return [.cola, .milk, .wine]
            case .hotBeverage:
                return [.coffee, .tea, .hotChocolate]
         }
    }
}

extension Beverage {
    var beverageType: BeverageType {
        switch self:
           case .cola:
                return .coldBeverage
           case .milk:
                return .coldBeverage
           //etc...
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用一个成员资格来定义另一个成员资格:

extension Beverage {
    static var beverages: [Beverage] {
        return [.cola, .milk, .wine, .coffee, .tea, .hotChocolate]
    }

    var type: BeverageType {
        switch self {
        case .cola, .milk, .wine:
            return .coldBeverage
        case .coffee, .tea, .hotChocolate:
            return .hotBeverage
        }
    }
}

extension BeverageType {
    var associatedBeverages: [Beverage] {
        return Beverage.beverages.filter { $0.type == self }
    }
}