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 {
    print(error.localizedDescription)
    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.

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Check out our book!

Integrating SwiftUI into UIKit Apps

Integrating SwiftUI intoUIKit Apps

UPDATED FOR iOS 17!

A detailed guide on gradually adopting SwiftUI in UIKit projects.

  • Discover various ways to add SwiftUI views to existing UIKit projects
  • Use Xcode previews when designing and building UI
  • Update your UIKit apps with new features such as Swift Charts and Lock Screen widgets
  • Migrate larger parts of your apps to SwiftUI while reusing views and controllers built in UIKit