Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting CustomError to ErrorType to NSError loses userInfo

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?

Edit

See my own answer here: https://stackoverflow.com/a/34033365/646960. Still not an optimal solution, feel free to propose a better one.

like image 573
ldiqual Avatar asked Sep 14 '15 19:09

ldiqual


1 Answers

Seems like preventing the compiler magic that casts ErrorType to NSError works well:

((error as Any) as! NSError).localizedDescription // "A great description"
like image 163
ldiqual Avatar answered Oct 24 '22 02:10

ldiqual