0

I defined a bunch of custom errors like this:

enum FilesystemError: Error {
    case cannotMove(String)
    case cannotDelete(String)
}

enum MediaError: Error {
    case cannotRecordVideo(String)
    case cannotLoadPhoto(String)
}

Now if an Error gets thrown I present it to the user using this helper function:

public func presentErrorAlert(presentingViewController: UIViewController, error: Error) {
    let title: String
    let message: String
    if let error = error as? FilesystemError {
        switch(error) {
        case .cannotMove(let msg):
            title = "Failed to move"
            message = msg
        case .cannotDelete(let msg):
            title = "Failed to delete"
            message = msg
        }
    }
    else if let error = error as? MediaError {
        switch(error) {
        case .cannotLoadPhoto(let msg):
            title = "Failed to load photo"
            message = msg
        case .cannotRecordVideo(let msg):
            title = "Failed to record video"
            message = msg
        }
    }
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
    presentingViewController.present(alert, animated: true, completion: nil)
}

I have a lot more errors in my code and way too much "message = msg" going on. It feels like there must be an easier way of doing this. Any ideas how to elegantly circumvent this?

  • Is this what you are looking for? [How to provide a localized description with an Error type in Swift?](https://stackoverflow.com/q/39176196/1187415) – Martin R Jun 25 '20 at 11:02

1 Answers1

0

let define:

protocol ErrorFormattable: Error {
    var errorTitle: String { get }
    var errorMessage: String { get }
}

make your error types conform ErrorFormattable. Then in presentErrorAlert, just check:

if let error = error as? ErrorFormattable {
    title = error.errorTitle
    message = error.errorMessage
}
nghiahoang
  • 538
  • 4
  • 10
  • There is already the `LocalizedError` protocol for that purpose. Compare https://stackoverflow.com/q/39176196/1187415. – Martin R Jun 25 '20 at 11:03
  • I was specifically asking how to retrieve the error message from an Enum instance complying to the Error protocol. I've only seen the described way of case .name(let msg) and was wondering why I can't just write name.message or something. I guess it's just not possible. – Call of Guitar Jul 26 '20 at 16:01