【问题标题】:Convert nested enumeration values into one variable to be passed as function parameters将嵌套枚举值转换为一个变量作为函数参数传递
【发布时间】:2016-02-26 18:38:34
【问题描述】:

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

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。有没有办法做到这一点?我认为这将涉及一个变量,该变量代表我可以传递给一个吃函数的所有嵌套变量类型。比如:

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"

这可能吗?

【问题讨论】:

  • @vadian 的回答很好,你可能还想看看stackoverflow.com/questions/35505655/…。要理解的重要一点是Vegetables 和Fruit 这里没有任何关系。 Food 除了创建命名空间外,什么都不做。除了名称之外,如果您去掉 Food,此代码将是相同的。这里没有保证您碰巧放入 Food 的每个枚举都会有一个 rawValue 属性。
  • 感谢您的回复。在这种情况下,我完全理解你对食物的意思。我将枚举器列表嵌套在命名空间中的唯一原因纯粹是出于组织目的,因为我的应用程序中有很多枚举列表。

标签: ios swift enums swift2 enumeration


【解决方案1】:

你可以使用协议

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    相关资源
    最近更新 更多