Trying to cast a CustomError
to compatible types (ErrorType, NSError) results in the user info dictionary being lost:
class CustomError: NSError {}
let error = CustomError(domain: "com.customerrorexample", code: 500, userInfo: [NSLocalizedDescriptionKey: "A great description"])
then
((error as ErrorType) as NSError).localizedDescription // "The operation couldn't be completed..."
However this will print the correct description:
((error as ErrorType) as! CustomError).localizedDescription // "A great description"
How come that ((CustomError as ErrorType) as NSError)
loses the userInfo dictionary? How can I work around it, knowing that my actual code will take an ErrorType
as input, and print its localizedDescription
- which should be accurate whatever the NSError subclass is?
See my own answer here: https://stackoverflow.com/a/34033365/646960. Still not an optimal solution, feel free to propose a better one.
Seems like preventing the compiler magic that casts ErrorType to NSError works well:
((error as Any) as! NSError).localizedDescription // "A great description"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With