Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- public struct SandwichError: Error, Equatable, CustomStringConvertible {
- private enum SandwichErrorCode: Int {
- case tooLittleSalami = 1
- case tooLittleMustard
- case noTomatoes
- case noBread
- }
- private var code: SandwichErrorCode
- private init(code: SandwichErrorCode) {
- self.code = code
- }
- public var description: String {
- return "SandwichError.\(String(describing: self.code))"
- }
- public static let tooLittleSalami: SandwichError = .init(code: .tooLittleSalami)
- public static let tooLittleMustard: SandwichError = .init(code: .tooLittleMustard)
- public static let noTomatoes: SandwichError = .init(code: .noTomatoes)
- public static let noBread: SandwichError = .init(code: .noBread)
- }
- func inspectErrorWithSwitch(_ error: Error) {
- if let error = error as? SandwichError {
- switch error {
- case .tooLittleSalami:
- print("NEED MORE SALAMI!")
- case .tooLittleMustard:
- print("NEED MORE MUSTARD!")
- case .noTomatoes:
- print("Can I please get a tomato?")
- default:
- print("ooh, some error I didn't know existed: \(error)")
- }
- } else {
- print("totally unexpected error")
- }
- }
- func inspectErrorWithCatch(_ e: Error) {
- do {
- throw e
- } catch let error as SandwichError where error == .tooLittleSalami {
- print("NEED MORE SALAMI!")
- } catch let error as SandwichError where error == .tooLittleMustard {
- print("NEED MORE MUSTARD!")
- } catch let error as SandwichError where error == .noTomatoes {
- print("Can I please get a tomato?")
- } catch let error as SandwichError {
- print("ooh, some error I didn't know existed: \(error)")
- } catch {
- print("totally unexpected error")
- }
- }
- inspectErrorWithSwitch(SandwichError.tooLittleSalami)
- inspectErrorWithSwitch(SandwichError.tooLittleMustard)
- inspectErrorWithSwitch(SandwichError.noTomatoes)
- inspectErrorWithSwitch(SandwichError.noBread)
- inspectErrorWithSwitch(NSError())
- inspectErrorWithCatch(SandwichError.tooLittleSalami)
- inspectErrorWithCatch(SandwichError.tooLittleMustard)
- inspectErrorWithCatch(SandwichError.noTomatoes)
- inspectErrorWithCatch(SandwichError.noBread)
- inspectErrorWithCatch(NSError())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement