Reputation: 13
I am new to Programming, i have to make a func that is used for search of an item, and if the item is found the recipe must be printed. Example:
enum Grocery {
case Wine
case Pork
case Onion
}
enum RecipePorkWithWine: String {
case Wine = "2 Glasses"
case Pork = "4 Pieces"
case Onion= "2 pcs"
How to make a func that search in the recipe and if the item is found the recipe should be printed.
Upvotes: 1
Views: 215
Reputation: 2632
define 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() }
}
}
usecase
Grocery.onion(num: 10).printRecipe()
Grocery.pork(num: 2).printRecipe()
when using receipt model
let receipt = Receipt()
receipt.add(grocery: .onion(num: 2))
receipt.add(grocery: .pork(num: 4))
receipt.add(grocery: .wine(num: 2))
receipt.printRecipe()
output
2 pcs
4 Pieces
2 Glasses
Upvotes: 3