Created
December 22, 2015 12:32
-
-
Save eofster/a3b9b9db531aa45bb59c to your computer and use it in GitHub Desktop.
Vending machine with long vend() function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Item { | |
var price: Int | |
var count: Int | |
} | |
enum VendingMachineError: ErrorType { | |
case InvalidSelection | |
case InsufficientFunds(coinsNeeded: Int) | |
case OutOfStock | |
} | |
class VendingMachine { | |
var inventory = [ | |
"Candy Bar": Item(price: 12, count: 7), | |
"Chips": Item(price: 10, count: 4), | |
"Pretzels": Item(price: 7, count: 11) | |
] | |
var coinsDeposited = 0 | |
func dispense(snack: String) { | |
print("Dispensing \(snack)") | |
} | |
func vend(itemNamed name: String) throws { | |
guard var item = inventory[name] else { | |
throw VendingMachineError.InvalidSelection | |
} | |
guard item.count > 0 else { | |
throw VendingMachineError.OutOfStock | |
} | |
guard item.price <= coinsDeposited else { | |
throw VendingMachineError.InsufficientFunds(coinsNeeded: item.price - coinsDeposited) | |
} | |
coinsDeposited -= item.price | |
--item.count | |
inventory[name] = item | |
dispense(name) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment