簡體   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