Fix: localizedDescription Ignores Your Custom Swift Error

Written by

in

Quick answer: A property named localizedDescription on your own error type is never consulted when the value is held as Error, because Foundation bridges it to NSError and builds a generic message. Conform to LocalizedError and implement errorDescription: String? instead, and the bridged localizedDescription returns your text without any casting.

Why this happens

Error is a bare protocol. It does not require a localizedDescription, and the compiler never searches your type for a property with that name. When you write error.localizedDescription on a value whose static type is Error, Foundation bridges the value to NSError and asks that for the description. The bridge only finds your text if the type adopts LocalizedError, or supplies NSLocalizedDescriptionKey through CustomNSError.

Your enum’s own var localizedDescription is just an ordinary member. It is used when the static type is MyError, and silently skipped when the value is held as Error — which is exactly how errors travel through throws, Result, completion handlers and catch blocks.

That is why you see The operation couldn’t be completed. (MyError error 0.): NSError built a default description from the domain and code because it found nothing better to show.

How to fix it

1. Adopt LocalizedError and implement errorDescription

The property name matters. It is errorDescription, it returns String?, and it lives on the LocalizedError protocol (available since Swift 3).

import Foundation

enum MyError: Error {
    case customError
}

extension MyError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .customError:
            return NSLocalizedString("A user-friendly description of the error.",
                                     comment: "My error")
        }
    }
}

let error: Error = MyError.customError
print(error.localizedDescription)
// A user-friendly description of the error.

No cast to MyError is needed, and the value can stay typed as Error all the way to the view or alert that displays it.

If the enum is public and lives in a framework, the conformance members must be public too, otherwise the bridging code in the app target cannot see them:

public extension MyError {
    var errorDescription: String? { /* ... */ }
}

You can also declare the conformance on the type itself (enum MyError: LocalizedError), since LocalizedError refines Error. An extension is usually cleaner when the enum is generated or already conforms to something else.

2. Add failureReason and recoverySuggestion

LocalizedError has two more optional properties. They surface on the bridged NSError as localizedFailureReason and localizedRecoverySuggestion, which is what system alerts and some frameworks read.

extension MyError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .customError:
            return NSLocalizedString("I failed.", comment: "")
        }
    }

    var failureReason: String? {
        switch self {
        case .customError:
            return NSLocalizedString("I don't know why.", comment: "")
        }
    }

    var recoverySuggestion: String? {
        switch self {
        case .customError:
            return NSLocalizedString("Switch it off and on again.", comment: "")
        }
    }
}

let error = MyError.customError as NSError
print(error.localizedDescription)         // I failed.
print(error.localizedFailureReason)       // Optional("I don't know why.")
print(error.localizedRecoverySuggestion)  // Optional("Switch it off and on again.")

Note the asymmetry: localizedDescription is available directly on Error, but localizedFailureReason and localizedRecoverySuggestion only exist on NSError, so you need the as NSError bridge to read them.

3. Use CustomNSError for domain, code and userInfo

If callers need a stable error domain, a numeric code, or extra payload, adopt CustomNSError. This controls what the bridge puts into the NSError it hands out.

extension MyError: CustomNSError {
    static var errorDomain: String { "com.example.myapp.MyError" }

    var errorCode: Int {
        switch self {
        case .customError:
            return 999
        }
    }

    var errorUserInfo: [String: Any] {
        switch self {
        case .customError:
            return ["line": 13]
        }
    }
}

let error = MyError.customError as NSError
print(error.code)   // 999
print(error.domain) // com.example.myapp.MyError

if let line = error.userInfo["line"] as? Int {
    print("Error in line", line) // Error in line 13
}

You do not need CustomNSError just to get a description — LocalizedError already covers that. Use it when the domain, code or payload actually matter to the caller.

4. Build messages for cases with associated values

Pattern-match the payload and interpolate it into a format string. Keep the format string itself localized so translators can reorder the arguments.

enum NetworkError: LocalizedError {
    case responseStatusError(status: Int, message: String)

    var errorDescription: String? {
        switch self {
        case let .responseStatusError(status, message):
            let format = NSLocalizedString(
                "The server returned status %d: %@",
                comment: "Network error with HTTP status code and server message"
            )
            return String(format: format, status, message)
        }
    }
}

Do not build the sentence with plain interpolation ("Error with status \(status)") if the app is localized — the surrounding words will never reach your translators. String(format:) keeps the sentence in the strings file and the values as arguments.

5. One-off errors without a custom type

For a single failure that does not deserve an enum, construct the NSError directly:

let error = NSError(
    domain: "com.example.myapp",
    code: 1,
    userInfo: [NSLocalizedDescriptionKey: "The file could not be read."]
)
print(error.localizedDescription) // The file could not be read.

This is fine for quick paths, but a typed enum with LocalizedError scales better once you need to switch on the failure.

How to prevent it

  • Never name a property localizedDescription on your own error type and expect it to be used. The bridge only reads errorDescription.
  • Adopt LocalizedError on every error enum that can reach a user-facing alert, banner or log line.
  • Return nil from errorDescription when you have nothing useful to say — an empty string produces a blank alert.
  • Test the message through an Error existential (let e: Error = MyError.customError), not through the concrete type. The concrete type hides the bug.
  • Use NSLocalizedString or String(localized:) with format strings for any message containing values.
  • Keep CustomStringConvertible.description for debugging output only; it is not what the user sees.

FAQ

Why is my custom localizedDescription property ignored?

Because localizedDescription on an Error value comes from the automatic bridge to NSError, not from a member of your type. The bridge looks for LocalizedError.errorDescription; anything else with a similar name is invisible to it.

Does LocalizedError still work if I convert the error to NSError?

Yes. errorDescription becomes NSLocalizedDescriptionKey in the bridged NSError, so (error as NSError).localizedDescription returns the same text.

Can structs and classes conform to LocalizedError?

Yes. Any type that conforms to Error can adopt it — enums, structs and classes alike. The only requirement is the optional errorDescription property.

Do I need both LocalizedError and CustomNSError?

No. LocalizedError handles the user-facing text. Add CustomNSError only when you also need a specific domain, error code or userInfo payload.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.