DEV Community

Cover image for How to use Error protocol easily in Swift
Shu
Shu

Posted on

2 2

How to use Error protocol easily in Swift

Swift has Error protocol that does not have anything default. iOS developers have to extend this protocol to deal with errors in their app. I will introduce a very simple example to manage custom errors. You can define your error cases like following.

// Error+Extension.swift

enum CustomError: Error {
    case errorOne
    case errorTwo
    case errorThree(message: String)
}

extension CustomError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .errorOne:
            return NSLocalizedString("Error one's description", comment: "Custom Error")
        case .errorTwo:
            return NSLocalizedString("Error two's description", comment: "Custom Error")
        case .errorThree(let message):
            return NSLocalizedString(message, comment: "Custom Error")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

I wrote an article about handling UIAlertController. Using this AlertController, Error+Extension.swift can be improved like this.

// Error+Extension.swift
enum CustomError: Error {
    case errorOne
    case errorTwo
    case errorThree(message: String)
}

extension CustomError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .errorOne:
            return NSLocalizedString("Error one's description", comment: "Custom Error")
        case .errorTwo:
            return NSLocalizedString("Error two's description", comment: "Custom Error")
        case .errorThree(let message):
            return NSLocalizedString(message, comment: "Custom Error")
        }
    }
}

extension Error {
    func displayAlert(completion: (() -> Void)? = nil) {
        let alert = AlertController(title: "Error", message: localizedDescription, preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default)
        alert.addAction(action)
        alert.show(completion: completion)
    }
}
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay