Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Error localizedDescription [duplicate]

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.

like image 986
Guig Avatar asked May 13 '26 17:05

Guig


1 Answers

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
like image 167
GetSwifty Avatar answered May 15 '26 08:05

GetSwifty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!