When I use the Result type in Swift, I have to define the error enum beforehand.
enum AppError: String, Error {
case error1 = "Error One."
case error2 = "Error Two."
}
So far so good, I can enumerate all possible errors that my app or function could raise. However, there are chances that I want to return dynamic error messages, for example the error messages returned from network. I don't find a way to return dynamic error message using Result type. I'm not sure if it is possible or not.
Update:
It turned out I don't need to use an enum at all. All I need is to define a class that implements Error.
I got it work like this:
class AppError: Error {
var message: String
init(_ message: String) {
self.message=message;
}
}
And to create an error like this:
completion(.failure(AppError("Invalid URL.")))
And to get back the error message like this:
error.message