Advertisement
Guest User

Untitled

a guest
Oct 13th, 2015
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1.  
  2. // This is a sample code snipet from The Swift Programmin Language(Swift2.1)
  3.  
  4. enum VendingMachineError: ErrorType {
  5. case InvalidSelection
  6. case InsufficientFunds(coinsNeeded: Int)
  7. case OutOfStock
  8. }
  9.  
  10. // Throwing error
  11. throw VendingMachineError.InsufficientFunds(coinsNeeded: 5)
  12.  
  13. struct Item {
  14. var price: Int
  15. var count: Int
  16. }
  17.  
  18. class VendingMachine
  19. {
  20. var inventory = [
  21. "Candy Bar": Item(price: 12, count: 7)
  22. "Chips": Item(price: 10, count: 4)
  23. "Pretzels": Item(price: 7, count: 11)
  24. ]
  25.  
  26. var coinsDeposited = 0
  27.  
  28. func dispenseSnack(snack: String) {
  29. print("Dispensing \(snack)")
  30. }
  31.  
  32. func vend(itemNamed name: String) throws {
  33. guard var item = inventory[name] else {
  34. throw VendingMachineError.InvalidSelection
  35. }
  36.  
  37. guard item.count > 0 else {
  38. throw VendingMachineError.OutOfStack
  39. }
  40.  
  41. guard item.price <= coinsDeposited else {
  42. throw VendingMachineError.InsufficientFunds(coinsNeeds: item.price - coinsDeposited)
  43. }
  44.  
  45. coinsDeposited -= item.price
  46. --item.count
  47. inventory[name] = item
  48. dispenceSnack(name)
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement