Can Swift Result Type return dynamic error message?

Viewed 490

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
2 Answers

You can define your error types to take a string argument that you can set in runtime

enum AppError: Error {
    case decodingError(String)
    case networkError(String)
}

Associated Values are great but unfortunately they only work with "plain" enums. I would suggest not using a String enum and instead to conform to CustomStringConvertible and use the description property to return the string value for your error.

enum AppError: Error, CustomStringConvertible {
    case error1
    case error2
    case customError(message: String)
    
    var description: String {
        switch self {
            case error1: return "Error 1"
            case error2: return "Error 2"
            case customError(let message): return message
        }
    }
}
Related