有没有一种很好的方法可以将不同的枚举分组到集合中来测试相互成员身份,而不需要大量的代码重复?
例如,下面,当我得到.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...
}
}
答案 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 }
}
}