将CustomError转换为ErrorType到NSError会丢失userInfo

ldi*_*ual 5 foundation swift xcode7 swift2

尝试CustomError强制转换为兼容类型(ErrorType,NSError)会导致用户信息字典丢失:

class CustomError: NSError {}

let error = CustomError(domain: "com.customerrorexample", code: 500, userInfo: [NSLocalizedDescriptionKey: "A great description"])
Run Code Online (Sandbox Code Playgroud)

然后

((error as ErrorType) as NSError).localizedDescription // "The operation couldn't be completed..."
Run Code Online (Sandbox Code Playgroud)

但是,这将打印正确的描述:

((error as ErrorType) as! CustomError).localizedDescription // "A great description"
Run Code Online (Sandbox Code Playgroud)

怎么会((CustomError as ErrorType) as NSError)失去userInfo字典?我怎么能解决它,知道我的实际代码将ErrorType作为输入,并打印它localizedDescription- 无论NSError子类是什么,它应该是准确的?

编辑

在这里看到我自己的答案: https //stackoverflow.com/a/34033365/646960.仍然不是最佳解决方案,随意提出一个更好的解决方案.

ldi*_*ual 6

似乎阻止将ErrorType强制转换为NSError的编译器魔法效果很好:

((error as Any) as! NSError).localizedDescription // "A great description"
Run Code Online (Sandbox Code Playgroud)