Quantcast
Channel: How to provide a localized description with an Error type in Swift? - Stack Overflow
Viewing all articles
Browse latest Browse all 8

How to provide a localized description with an Error type in Swift?

$
0
0

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.customErrorerror.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?


Viewing all articles
Browse latest Browse all 8

Latest Images

Trending Articles





Latest Images