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

时间:2016-02-26 18:38:34

标签: ios swift enums swift2 enumeration

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

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.有没有办法做到这一点?我想它会涉及一个变量,它代表我可以传递给一个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"

这可能吗?

1 个答案:

答案 0 :(得分:5)

您可以使用协议

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"