简体   繁体   中英

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? 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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM