Reputation: 3053
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? I figure it would involve a variable that represents all nested variable types that I could pass into one eat function. 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?
Upvotes: 0
Views: 167
Reputation: 285082
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
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"
Upvotes: 5