Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. import Foundation
  2.  
  3. public struct SandwichError: Error, Equatable, CustomStringConvertible {
  4. private enum SandwichErrorCode: Int {
  5. case tooLittleSalami = 1
  6. case tooLittleMustard
  7. case noTomatoes
  8. case noBread
  9. }
  10.  
  11. private var code: SandwichErrorCode
  12.  
  13. private init(code: SandwichErrorCode) {
  14. self.code = code
  15. }
  16.  
  17. public var description: String {
  18. return "SandwichError.\(String(describing: self.code))"
  19. }
  20.  
  21. public static let tooLittleSalami: SandwichError = .init(code: .tooLittleSalami)
  22. public static let tooLittleMustard: SandwichError = .init(code: .tooLittleMustard)
  23. public static let noTomatoes: SandwichError = .init(code: .noTomatoes)
  24. public static let noBread: SandwichError = .init(code: .noBread)
  25. }
  26.  
  27. func inspectErrorWithSwitch(_ error: Error) {
  28. if let error = error as? SandwichError {
  29. switch error {
  30. case .tooLittleSalami:
  31. print("NEED MORE SALAMI!")
  32. case .tooLittleMustard:
  33. print("NEED MORE MUSTARD!")
  34. case .noTomatoes:
  35. print("Can I please get a tomato?")
  36. default:
  37. print("ooh, some error I didn't know existed: \(error)")
  38. }
  39. } else {
  40. print("totally unexpected error")
  41. }
  42. }
  43.  
  44. func inspectErrorWithCatch(_ e: Error) {
  45. do {
  46. throw e
  47. } catch let error as SandwichError where error == .tooLittleSalami {
  48. print("NEED MORE SALAMI!")
  49. } catch let error as SandwichError where error == .tooLittleMustard {
  50. print("NEED MORE MUSTARD!")
  51. } catch let error as SandwichError where error == .noTomatoes {
  52. print("Can I please get a tomato?")
  53. } catch let error as SandwichError {
  54. print("ooh, some error I didn't know existed: \(error)")
  55. } catch {
  56. print("totally unexpected error")
  57. }
  58. }
  59.  
  60. inspectErrorWithSwitch(SandwichError.tooLittleSalami)
  61. inspectErrorWithSwitch(SandwichError.tooLittleMustard)
  62. inspectErrorWithSwitch(SandwichError.noTomatoes)
  63. inspectErrorWithSwitch(SandwichError.noBread)
  64. inspectErrorWithSwitch(NSError())
  65.  
  66. inspectErrorWithCatch(SandwichError.tooLittleSalami)
  67. inspectErrorWithCatch(SandwichError.tooLittleMustard)
  68. inspectErrorWithCatch(SandwichError.noTomatoes)
  69. inspectErrorWithCatch(SandwichError.noBread)
  70. inspectErrorWithCatch(NSError())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement