Created
January 8, 2016 19:55
-
-
Save cellularmitosis/9a175facd5fe260403f1 to your computer and use it in GitHub Desktop.
Modified version of code from blog post https://medium.com/swift-programming/why-swift-guard-should-be-avoided-484cfc2603c5#.y8wcikeez
This file contains hidden or 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
//: Playground - noun: a place where people can play | |
import UIKit | |
//: Playground - noun: a place where people can play | |
import UIKit | |
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 { | |
let item = try validatedItemNamed(name) | |
reduceDepositedCoinsBy(item.price) | |
removeFromInventory(item, name: name) | |
dispense(name) | |
} | |
private func validatedItemNamed(name: String) throws -> Item { | |
let item = try itemNamed(name) | |
try validate(item) | |
return item | |
} | |
private func reduceDepositedCoinsBy(price: Int) { | |
coinsDeposited -= price | |
} | |
private func removeFromInventory(var item: Item, name: String) { | |
--item.count | |
inventory[name] = item | |
} | |
private func itemNamed(name: String) throws -> Item { | |
guard let item = inventory[name] else { | |
throw VendingMachineError.InvalidSelection | |
} | |
return item | |
} | |
private func validate(item: Item) throws { | |
try validateCount(item.count) | |
try validatePrice(item.price) | |
} | |
private func validateCount(count: Int) throws { | |
guard count > 0 else { | |
throw VendingMachineError.OutOfStock | |
} | |
} | |
private func validatePrice(price: Int) throws { | |
guard coinsDeposited >= price else { | |
throw VendingMachineError.InsufficientFunds(coinsNeeded: price - coinsDeposited) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment