如何在枚举Swift 3.0中访问和制作一个函数

时间:2016-12-17 16:02:49

标签: swift

我是编程新手,我必须制作一个用于编程的函数 搜索项目,如果找到该项目,则必须打印该配方。例如:

enum Grocery  {
    case Wine
    case Pork
    case Onion
}
enum RecipePorkWithWine: String {
    case Wine = "2 Glasses"
    case Pork = "4 Pieces"
    case Onion= "2 pcs"

如何制作一个在食谱中搜索的功能,如果找到该项目,则应打印食谱。

1 个答案:

答案 0 :(得分:3)

定义Grocery,Receipt

enum Grocery  {
  case wine(num: Int)
  case pork(num: Int)
  case onion(num: Int)

  func printRecipe() {
    switch self {
    case .wine(let num): print("\(num) Glasses")
    case .pork(let num): print("\(num) Pieces")
    case .onion(let num): print("\(num) pcs")
    }
  }
}

class Receipt {
  var grocerys: [Grocery] = []

  func add(grocery: Grocery) {
    grocerys.append(grocery)
  }

  func printRecipe() {
    grocerys.forEach { $0.printRecipe() }
  }
}

用例

Grocery.onion(num: 10).printRecipe()

Grocery.pork(num: 2).printRecipe()

使用收据模型时

let receipt = Receipt()
receipt.add(grocery: .onion(num: 2))
receipt.add(grocery: .pork(num: 4))
receipt.add(grocery: .wine(num: 2))
receipt.printRecipe()

输出

2 pcs
4 Pieces
2 Glasses