WWDC24 deal: 30% off our Swift and SwiftUI books! Learn more ...WWDC24 deal:30% off our Swift and SwiftUI books >>

User-friendly descriptions and recovery suggestions for custom errors in Swift

Creating a seamless user experience in Swift involves not just managing errors but also communicating them effectively. By defining user-friendly descriptions and recovery suggestions for custom errors, we can guide users through resolving issues, making our applications more intuitive and supportive.

We can begin by categorizing our custom errors using an enum. Then we should make the enum conform to the LocalizedError protocol to enrich the errors with detailed, localized descriptions and actionable recovery suggestions.

import Foundation

enum NetworkError: Error {
    case disconnected
    case timeout

extension NetworkError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .disconnected:
            return "Unable to connect to the network."
        case .timeout:
            return "The request timed out."

    var recoverySuggestion: String? {
        switch self {
        case .disconnected:
            return "Please check your internet connection and try again."
        case .timeout:
            return "Please check your network speed or try again later."

When our application encounters an error, we can handle it gracefully by providing the user with a clear understanding of what went wrong and how they can fix it.

do {
    // Some network operation that might throw
} catch let error as NetworkError {
    if let suggestion = error.recoverySuggestion {
        print("Suggestion: \(suggestion)")
} catch {
    print("An unexpected error occurred: \(error.localizedDescription)")

By defining user-friendly descriptions and recovery suggestions for custom errors, we can transform technical setbacks into helpful guidance. This approach not only enhances the user experience but also empowers users to resolve issues proactively, making our Swift applications more robust and user-centric.

If you're an experienced Swift developer looking to learn advanced techniques, check out my new book Swift Gems. It’s packed with tips and tricks focused solely on the Swift language and Swift Standard Library. From optimizing collections and handling strings to mastering asynchronous programming and debugging, "Swift Gems" provides practical advice that will elevate your Swift development skills to the next level. Grab your copy of Swift Gems and let's explore these advanced techniques together.

Books by Natalia PanferovaBooks by Natalia Panferova
WWDC24: 30% off all books!
  • Swift Gems

    100+ tips to take your Swift code to the next level

  • Integrating SwiftUI into UIKit Apps

    A detailed guide on gradually adopting SwiftUI in UIKit projects

The offer is active until the 16th of June.