I am defining a custom error type with Swift 3 syntax and I want to provide a user-friendly description of the error which is returned by the localizedDescription
property of the Error
object. How can I do it?
public enum MyError: Error {
case customError
var localizedDescription: String {
switch self {
case .customError:
return NSLocalizedString("A user-friendly description of the error.", comment: "My error")
}
}
}
let error: Error = MyError.customError
error.localizedDescription
// "The operation couldn’t be completed. (MyError error 0.)"
Is there a way for the localizedDescription
to return my custom error description ("A user-friendly description of the error.")? Note that the error object here is of type Error
and not MyError
. I can, of course, cast the object to MyError
(error as? MyError)?.localizedDescription
but is there a way to make it work without casting to my error type?
There are now two Error-adopting protocols that your error type can adopt in order to provide additional information to Objective-C — LocalizedError and CustomNSError. Here's an example error that adopts both of them:
I would also add, if your error has parameters like this
you can call these parameters in your localized description like this:
You can even make this shorter like this:
As described in the Xcode 8 beta 6 release notes,
In your case:
You can provide even more information if the error is converted to
NSError
(which is always possible):By adopting the
CustomNSError
protocol the error can provide auserInfo
dictionary (and also adomain
andcode
). Example:Using a struct can be an alternative. A little bit elegance with static localization:
Here is more elegant solution: