繁体   English   中英

将嵌套的枚举值转换为一个变量以作为函数参数传递

[英]Convert nested enumeration values into one variable to be passed as function parameters

我不确定这是否可行,但我想知道是否有可能将嵌套的枚举值转换为单个变量,以便可以将其传递给函数参数。 例:

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"

此处的所有功能均应正常运行,但我试图将我的两个eat函数合并为1。有没有办法做到这一点? 我认为它将涉及一个变量,该变量代表我可以传递给一个eat函数的所有嵌套变量类型。 就像是:

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"

这可能吗?

您可以使用协议

protocol Vegetarian {
  var rawValue : String { get }
}

并将其添加到两个枚举

enum Vegetables: String, Vegetarian { ... }
enum Fruit: String, Vegetarian { ... }

那你就可以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.

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