Throwing errors
This is kind of cool, but what does your program do with these errors? It throws them, of course! That’s the actual terminology you’ll see: throwing errors, and then catching them.
Add this class to your playground:
class Bakery {
var itemsForSale = [
"Cookie": Pastry(flavor: "ChocolateChip", numberOnHand: 20), "PopTart": Pastry(flavor: "WildBerry", numberOnHand: 13), "Donut" : Pastry(flavor: "Sprinkles", numberOnHand: 24), "HandPie": Pastry(flavor: "Cherry", numberOnHand: 6)
]
func orderPastry(item: String,
amountRequested: Int,
flavor: String) throws -> Int { guard let pastry = itemsForSale[item] else {
throw BakeryError.doNotSell
}
guard flavor == pastry.flavor else { throw BakeryError.wrongFlavor
}
guard amountRequested < pastry.numberOnHand else {
throw BakeryError.tooFew(numberOnHand: pastry.numberOnHand)
}
pastry.numberOnHand -= amountRequested
return pastry.numberOnHand
}
}
First off you need to have some items to sell. Each item needs to have a flavor and an amount on hand. When the customer orders a pastry from you, they need to tell you what pastry they want, what flavor they want, and how many they want.
Customers can be incredibly demanding. :]
First, you need to check if you even carry what the customer wants. If the customer tries to order albatross with wafers, you don’t want the bakery to crash.
After you verify that the bakery actually carries the item the customer wants, you need to check if you have the requested flavor and if you have enough of that item to fulfill the customer’s order.
let bakery = Bakery() bakery.orderPastry(item: "Albatross",
amountRequested: 1, flavor: "AlbatrossFlavor")
The code above crashes the program. What went wrong? You threw your error, so why are you crashing?
Oh right — you need to catch the error and do something with it.