Last active
February 22, 2016 03:07
-
-
Save bharath2020/015e511eed2e9f2479a7 to your computer and use it in GitHub Desktop.
VendingMachine Test Cases
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 dispenseSnack(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 | |
dispenseSnack(name) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment