Senger CodeLab πŸš€

How to provide a localized description with an Error type in Swift

September 29, 2026

How to provide a localized description with an Error type in Swift

Creating informative and user-friendly error messages is crucial for any successful app. In Swift, providing localized descriptions for custom error types ensures a seamless experience for users worldwide. This allows your app to communicate errors effectively, regardless of the user’s preferred language. This article delves into the best practices for localizing error descriptions in Swift, empowering you to create a more robust and globally accessible application.

Defining Custom Error Types

The foundation of effective error handling lies in defining clear and descriptive error types. In Swift, this is achieved using the Error protocol. By conforming to this protocol, you can create custom error types that encapsulate specific error conditions within your application. This allows for more granular error handling and facilitates targeted localization efforts.

For instance, imagine a network request that might fail due to various reasons. Instead of relying on a generic error message, you could define separate error cases for issues like invalidURL, timeout, or serverError. This not only improves code clarity but also allows you to tailor localized descriptions for each specific error scenario.

Implementing LocalizedError Protocol

Swift’s LocalizedError protocol provides the tools needed to create user-friendly error descriptions. This protocol requires implementing the errorDescription and failureReason properties, which are automatically used by system frameworks to display error information to the user. By localizing these properties, you can ensure that error messages are presented in the user’s preferred language.

Here’s how you can implement the LocalizedError protocol:

enum NetworkError: Error, LocalizedError { case invalidURL case timeout case serverError var errorDescription: String? { switch self { case .invalidURL: return NSLocalizedString("invalidURL_description", comment: "Invalid URL") case .timeout: return NSLocalizedString("timeout_description", comment: "Request timed out") case .serverError: return NSLocalizedString("serverError_description", comment: "Server error") } } } 

This approach utilizes NSLocalizedString, a powerful function that retrieves localized strings from your app’s string files. This allows for easy management and translation of error messages into multiple languages.

Leveraging String Files for Localization

String files (.strings files) are the backbone of localization in iOS and macOS development. These files store key-value pairs, where the key is a unique identifier for a string, and the value is the translated string for a particular language. By organizing your localized strings into these files, you can efficiently manage translations and ensure consistency across your app.

For our NetworkError example, the corresponding entries in your Localizable.strings file might look like this:

"invalidURL_description" = "The URL provided is invalid."; "timeout_description" = "The request timed out."; "serverError_description" = "A server error occurred."; 

These entries provide the English translations for our error descriptions. You can then create separate .strings files for each language you want to support, such as Localizable.strings (fr) for French or Localizable.strings (es) for Spanish. This structure enables seamless localization without modifying your codebase.

Best Practices for Localized Error Handling

To create truly user-friendly localized error messages, consider these best practices:

  • Be Concise and Specific: Provide clear, concise descriptions of the error, avoiding technical jargon.
  • Offer Solutions: Whenever possible, suggest actions the user can take to resolve the error.

For example, if a network request fails due to a timeout, instead of simply stating “Request timed out,” a more helpful message could be “The request timed out. Please check your internet connection and try again.” This provides the user with actionable steps to address the issue.

For more advanced scenarios, consider using error codes and providing links to online documentation. This allows users to find detailed information about the error and its potential solutions. For instance: “A server error occurred (Error Code: 500). See more details.”

Handling Localized Errors in Practice

Here’s an example of how you might handle a localized error in your code:

do { // Perform some operation that might throw an error } catch let error as NetworkError { print(error.localizedDescription) } catch { print("An unknown error occurred.") } 

By catching the specific error type (NetworkError in this case) and accessing its localizedDescription property, you can present the user with a translated error message appropriate for their locale. This ensures a consistent and user-friendly experience regardless of language settings.

Placeholder for Infographic: [Infographic illustrating the process of localizing error descriptions in Swift]

  1. Define your custom error type.
  2. Conform to the LocalizedError protocol.
  3. Use NSLocalizedString to access localized strings.
  4. Create and maintain your .strings files for each supported language.

Featured Snippet Optimization: To localize error descriptions effectively in Swift, leverage the LocalizedError protocol and NSLocalizedString function. Store your translated strings in .strings files for easy management and ensure your error messages are clear, concise, and offer potential solutions.

By following these best practices and utilizing the tools provided by Swift, you can enhance the user experience and create a truly global application. Accurately translated error messages not only improve usability but also contribute to a more professional and polished product. This level of attention to detail will undoubtedly be appreciated by users worldwide. Now you have the knowledge to create robust and user-friendly localized error handling in your Swift applications. Learn more about advanced localization techniques. Explore Apple’s documentation on Internationalization and Localization for a comprehensive guide to creating globalized apps. Further resources include [link to external resource 1], [link to external resource 2], and [link to external resource 3].

Frequently Asked Questions

Q: What is the difference between errorDescription and failureReason?

A: errorDescription provides a concise description of the error suitable for displaying to the user. failureReason offers a more detailed explanation of why the error occurred, which can be useful for debugging or logging purposes.

Q: How do I test localized error messages?

A: You can test localized error messages by changing your device’s language settings or using Xcode’s localization testing tools.

Question & Answer :
I am defining a custom error type with Swift 3 syntax and I want to provide a user-friendly description of the error which is returned by the localizedDescription property of the Error object. How can I do it?

public enum MyError: Error { case customError var localizedDescription: String { switch self { case .customError: return NSLocalizedString("A user-friendly description of the error.", comment: "My error") } } } let error: Error = MyError.customError error.localizedDescription // "The operation couldn’t be completed. (MyError error 0.)" 

Is there a way for the localizedDescription to return my custom error description (“A user-friendly description of the error.”)? Note that the error object here is of type Error and not MyError. I can, of course, cast the object to MyError

(error as? MyError)?.localizedDescription 

but is there a way to make it work without casting to my error type?

As described in the Xcode 8 beta 6 release notes,

Swift-defined error types can provide localized error descriptions by adopting the new LocalizedError protocol.

In your case:

public enum MyError: Error { case customError } extension MyError: LocalizedError { public 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. 

You can provide even more information if the error is converted to NSError (which is always possible):

extension MyError : LocalizedError { public var errorDescription: String? { switch self { case .customError: return NSLocalizedString("I failed.", comment: "") } } public var failureReason: String? { switch self { case .customError: return NSLocalizedString("I don't know why.", comment: "") } } public 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.") 

By adopting the CustomNSError protocol the error can provide a userInfo dictionary (and also a domain and code). Example:

extension MyError: CustomNSError { public static var errorDomain: String { return "myDomain" } public var errorCode: Int { switch self { case .customError: return 999 } } public var errorUserInfo: [String : Any] { switch self { case .customError: return [ "line": 13] } } } let error = MyError.customError as NSError if let line = error.userInfo["line"] as? Int { print("Error in line", line) // Error in line 13 } print(error.code) // 999 print(error.domain) // myDomain