Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This is a sample code snipet from The Swift Programmin Language(Swift2.1)
- enum VendingMachineError: ErrorType {
- case InvalidSelection
- case InsufficientFunds(coinsNeeded: Int)
- case OutOfStock
- }
- // Throwing error
- throw VendingMachineError.InsufficientFunds(coinsNeeded: 5)
- struct Item {
- var price: Int
- var count: Int
- }
- 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.OutOfStack
- }
- guard item.price <= coinsDeposited else {
- throw VendingMachineError.InsufficientFunds(coinsNeeds: item.price - coinsDeposited)
- }
- coinsDeposited -= item.price
- --item.count
- inventory[name] = item
- dispenceSnack(name)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement