[英]Convert nested enumeration values into one variable to be passed as function parameters
I'm not sure if this is possible but I was wondering if it's possible to convert nested enumeration values into a single variable so that they can be passed into a function parameter. 我不确定这是否可行,但我想知道是否有可能将嵌套的枚举值转换为单个变量,以便可以将其传递给函数参数。 Example: 例:
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"
Everything here works as it should but I'm trying to consolidate my two eat functions into 1. Is there a way to do that? 此处的所有功能均应正常运行,但我试图将我的两个eat函数合并为1。有没有办法做到这一点? I figure it would involve a variable that represents all nested variable types that I could pass into one eat function. 我认为它将涉及一个变量,该变量代表我可以传递给一个eat函数的所有嵌套变量类型。 Something like: 就像是:
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"
Is this possible? 这可能吗?
You could use a protocol 您可以使用协议
protocol Vegetarian {
var rawValue : String { get }
}
and add it to both enums 并将其添加到两个枚举
enum Vegetables: String, Vegetarian { ... }
enum Fruit: String, Vegetarian { ... }
Then you can declare eat
那你就可以eat
func eat(meal:Vegetarian) {
print("I just ate some \(meal.rawValue)")
}
eat(Food.Vegetables.GreenBeans) //"I just ate some Green Beans\n"
eat(Food.Fruit.Grapes) //"I just ate some Grapes\n"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.