How to add localized description for errors in Swift (Error protocol)
Hi everyone! I'm writing my app in Swift 3 and encountered a problem with localizing error messages. I have my own error type implementing the Error protocol:
enum MyError: Error {
case networkError
case invalidInput(String)
case unknown
}
I want the user to see a clear message in their language when an error occurs. I know about NSLocalizedString, but I don't understand how to properly integrate it with Error. I tried doing this:
extension MyError: LocalizedError {
var errorDescription: String? {
switch self {
case .networkError:
return NSLocalizedString("Network error", comment: "Network error")
case .invalidInput(let field):
return NSLocalizedString("Invalid input in", comment: "Invalid input in")
}
}
} No answers yet.
Log in to leave an answer