1

Consider the simple code below:

func showError(error: Error) {
    debugPrint("A", error)
    debugPrint("B", error.localizedDescription)
    if let myError = error as? BarError {
        debugPrint("C", myError.localizedDescription)
    }
}

The following code outputs:

"A" external error: La connexion Internet semble interrompue.
"B" "L’opération n’a pas pu s’achever. (Foo.BarError erreur 0.)"
"C" "An error happened. My description. (external error: La connexion Internet semble interrompue.)"

How come .localizedDescription does not return the same message depending on what type the compiler thinks the object is?

Here is the code for BarError:

public enum BarError: Error, CustomStringConvertible {
    case a
    case b
    case externalError(Error)

    var localizedDescription: String {
        return "An error happened. My description. (\(self))"
    }

    public var description: String {
        switch self {
        case .a:
            return "A"
        case .b:
            return "B"
        case .externalError(let error):
            return "external error: \(error.localizedDescription)"
    }
}
Mick F
  • 7,312
  • 6
  • 51
  • 98
  • Thanks @MartinR. The post you're linking to is a nice solution to my problem. But it is still a weird behavior from a language perspective. – Mick F Nov 20 '17 at 16:19
  • 2
    `var localizedDescription` is not a *requirement* of `protocol Error` but defined in a protocol extension. As a consequence, it is statically dispatched, not dynamically (see e.g. https://oleb.net/blog/2016/06/kevin-ballard-swift-dispatch/). That's why the result depends on the type on which the method is called. – Martin R Nov 20 '17 at 16:27

0 Answers0