In Swift, why does a custom error's localizedDescription read "The operation couldn’t be completed", and how does LocalizedError fix it?
answer
- a Foundation extension, not Error
- bridged through NSError
- four optional strings
- description is not enough
basics
~20 sFoundation adds localizedDescription to every Error by bridging it to NSError; a plain error type has no localized text, so you get a generic sentence with its type name and code. Implementing LocalizedError's errorDescription supplies the real message.
solid answer
~30 s`localizedDescription` is not part of `Error`; it is a Foundation extension that bridges the value to `NSError`. A plain enum gives the bridge nothing to say, so it prints "The operation couldn’t be completed. (Module.ValidationError error 0.)". Conform the type to `LocalizedError` and return a message from `errorDescription`, and every `error.localizedDescription`, including through `any Error`, shows it; `failureReason` and `recoverySuggestion` fill the other `NSError` fields. Implementing `CustomStringConvertible` only changes `print` output, and declaring your own `localizedDescription` property is ignored through `any Error`, because the extension member is not dynamically dispatched.
code
swift · 23 linesimport Foundation
enum ValidationError: Error, CustomStringConvertible {
case badEmail(line: Int)
var description: String {
switch self { case .badEmail(let line): "Row \(line) has an invalid email address." }
}
}
enum ImportError: LocalizedError {
case badEmail(line: Int)
var errorDescription: String? {
switch self { case .badEmail(let line): "Row \(line) has an invalid email address." }
}
var recoverySuggestion: String? { "Fix the address in the file and import again." }
}
struct ShadowError: Error { var localizedDescription: String { "shadowed text" } }
let errors: [any Error] = [ValidationError.badEmail(line: 4), ImportError.badEmail(line: 4), ShadowError()]
for error in errors {
print(error.localizedDescription)
}go deeper
Recall that LocalizedError and its errorDescription property give an error readable text, and that the generic message means it is missing.
Explain the NSError bridge behind localizedDescription, the four LocalizedError properties, and why description and a same-named property do not help.
Show how you keep error cases for control flow and wording in errorDescription, and convert stage errors into one user-facing type at the presentation layer.
Discuss where user-facing wording should live in an app's layers and when bridging details such as CustomNSError domains and codes are worth exposing.
## Where localizedDescription comes from `localizedDescription` is **not** a requirement of the `Error` protocol. Foundation adds it in an extension, `extension Error { public var localizedDescription: String { get } }`, and computes it by bridging the error to `NSError` and asking for its localized description. That is why the property exists only in files that import Foundation. For a plain Swift error type, the bridge has no localized text to offer, so Foundation falls back to a generic sentence built from the type's name and a numeric code: ```plaintext The operation couldn’t be completed. (CSVImport.ValidationError error 0.) ``` The prefix is the module that declares the type (here a module named `CSVImport`), and the number is the bridged error code that Swift derives from the value. For an enum it comes from the compiler's internal numbering of cases, which is not reliably the declaration order, so never treat it as stable data. ## LocalizedError supplies the text Foundation's `LocalizedError` protocol refines `Error` and declares four optional strings. Each has a default implementation returning `nil`, so you implement only the ones you need: | Property | Bridged to | Typical content | |---|---|---| | `errorDescription` | `localizedDescription` | what went wrong, in one sentence | | `failureReason` | `NSError.localizedFailureReason` | why it went wrong | | `recoverySuggestion` | `NSError.localizedRecoverySuggestion` | what the user can do | | `helpAnchor` | `NSError.helpAnchor` | a help-book anchor | Conforming the CSV importer's error to `LocalizedError` and returning "Row 4 has an invalid email address." from `errorDescription` changes what every `error.localizedDescription` shows, including through `any Error`, which is how alerts and logs usually reach it. Returning `nil` for a case falls back to the generic sentence. ## Traps that look like fixes Three attempts compile and change nothing that an alert shows: - **`CustomStringConvertible`.** A `description` property changes what `print(error)` and string interpolation produce, but `localizedDescription` still uses the bridge and shows the generic sentence. - **A property named `localizedDescription` on your own type.** It shadows Foundation's member only when the static type is your concrete type. Through `any Error` the call resolves to Foundation's extension, because the name is not a protocol requirement and so is not dynamically dispatched. In the example, `ShadowError` prints the generic sentence inside the loop. - **`LocalizedError` with the wrong property.** Implementing only `recoverySuggestion` leaves `localizedDescription` fully generic, and implementing only `failureReason` appends the reason to "The operation couldn’t be completed." instead of replacing the sentence. ## Reading the example The loop holds three errors as `any Error` and prints `localizedDescription` for each: 1. `ValidationError` implements `description`, so `print(error)` would show the friendly sentence, but `localizedDescription` still prints the generic text with code 0. 2. `ImportError` conforms to `LocalizedError`, so the bridge returns its `errorDescription`: "Row 4 has an invalid email address." 3. `ShadowError` declares its own `localizedDescription`; through `any Error` it is ignored and the generic text appears. Calling `ShadowError().localizedDescription` on the concrete type would print "shadowed text", which is what makes the bug hard to spot in a quick test. ## Choosing the shape of a user-facing error 1. Keep the **cases** for code: they carry the data a caller needs (`line: Int`), and `catch` patterns match on them. 2. Put **wording** in `errorDescription`, computed from those cases, so display text never drives control flow. 3. Use `CustomNSError` (with `errorDomain`, `errorCode` and `errorUserInfo`) only when the error must look a specific way to Objective-C or to code that reads `NSError` domains and codes. 4. Keep internal stage errors plain and convert them into one `LocalizedError` type at the layer that talks to the user. Localising the strings themselves is a Foundation and app concern; the language-level point is which protocol property the bridge reads.
- Why does adding var localizedDescription: String to an error struct not change what an alert shows?The alert code usually holds the value as `any Error`, and `localizedDescription` there resolves to Foundation's extension on `Error`. Your property is not a protocol requirement, so it is not dispatched dynamically; it shadows the extension only when the static type is your struct. Conform to `LocalizedError` and implement `errorDescription` instead.
- What do the type name and number in "(CSVImport.ValidationError error 0.)" tell you?They come from bridging to `NSError`: the domain is the module-qualified type name, and the code is a number Swift derives from the enum case, not reliably its declaration order. Conforming to `CustomNSError` lets you set `errorDomain`, `errorCode` and `errorUserInfo` yourself when Objective-C or logging code relies on stable values.
- Where does recoverySuggestion from LocalizedError show up?Bridging maps it to `NSError.localizedRecoverySuggestion`, so `(error as NSError).localizedRecoverySuggestion` returns your text. UI code that builds an alert from an `NSError`, or your own presentation layer, can show it under the main message from `errorDescription`.
- Conforming to CustomStringConvertible changes localizedDescription.
- A localizedDescription property on my error type overrides it everywhere.
- LocalizedError forces you to implement all four of its properties.
- localizedDescription is a requirement declared by the Error protocol itself.
- Implementing recoverySuggestion alone is enough to replace the generic message.