0
我不确定这是否可能,但我想知道是否可以将嵌套的枚举值转换为单个变量,以便它们可以传入函数参数。例如:将嵌套的枚举值转换为一个变量作为函数参数传递
enum Food {
enum Vegetables: String {
case Spinach = "Spinach"
case GreenBeans = "Green Beans"
}
enum Fruit: String {
case Apples = "Apples"
case Grapes = "Grapes"
}
}
func eat(meal:Food.Vegetables) {
print("I just ate some \(meal.rawValue)")
}
func eat(meal:Food.Fruit) {
print("I just ate some \(meal.rawValue)")
}
eat(Food.Fruit.Apples) //"I just ate some Spinach\n"
eat(Food.Vegetables.Spinach) //"I just ate some Apples\n"
这里的一切工作,因为它应该,但我想巩固我的两个吃功能到1.有没有办法做到这一点?我想它会涉及一个变量,它表示所有可以传入一个吃饭功能的嵌套变量类型。例如:
func eat(fruitOrVegetable: Food.allNestedEnumeratorTypes) {
print("I just ate some \(fruitOrVegetable.rawValue)")
}
eat(Food.Vegetables.GreenBeans) //"I just ate some Green Beans\n"
eat(Food.Vegetables.Grapes) //"I just ate some Grapes\n"
这可能吗?
@ vadian的回答是好,你也可以想看看http://stackoverflow.com/questions/35505655/adopting-equatable-protocol-for-enum-with-nested-enum-value S/35506786#35506786。重要的是要明白'蔬菜'和'水果'在这里没有任何关系。除了创建一个命名空间外,“食物”完全没有任何功能。除了名字,如果你摆脱了“食物”,这段代码将是相同的。在这里没有承诺,你碰巧把每个枚举放在'Food'中都会有'rawValue'属性。 –
感谢您的回复。在这种情况下,我完全理解你对食物的含义。我将枚举器列表嵌套在命名空间中的唯一原因纯粹是为了组织目的,因为我的应用程序中有许多枚举列表。 – DJSK