DEV Community

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

Posted on

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

Top comments (0)