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?