NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Learn more...

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.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Check out our new book!

Swift Gems

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

Swift Gems

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

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift