I've an error class that is:
public enum ModelError: Error {
case invalidArray(model: String)
var localizedDescription: String {
switch self {
case .invalidArray(model: let model):
return "\(model) has an invalid array"
default:
return "modelError"
}
}
}
and when passed as an Error in a callback function, I want to access its custom localizedDescription. For instance:
func report(_ error: Error) {
print("Error report: \(error.localizedDescription)")
}
But calling report(ModelError.invalidArray(model: "test")) prints:
"The operation couldn’t be completed. (ModelError error 0.)"
Such things seems feasible with NSError since I can override the localizedDescription property there. But I don't want to use NSError since it's not really a swift thing and a lot of libraries work with Error.
According to the Documentation, localizedDescription is implemented in a protocol extension, not in the protocol declaration, which means there's nothing to adhere to or override. There is a type-wide interface for enums that adhere to Error.
My way I get around this is to use a wrapper protocol:
protocol LocalizedDescriptionError: Error {
var localizedDescription: String { get }
}
public enum ModelError: LocalizedDescriptionError {
case invalidArray(model: String)
var localizedDescription: String {
switch self {
case .invalidArray(model: let model):
return "\(model) has an invalid array"
default:
return "modelError"
}
}
}
let error: LocalizedDescriptionError = ModelError.invalidArray(model: "Model")
let text = error.localizedDescription // Model Has an invalid array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With