将ErrorType转换为NSError会丢失关联的对象 [英] Converting ErrorType to NSError loses associated objects
本文介绍了将ErrorType转换为NSError会丢失关联的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Swift 2.0中 NSError
符合 ErrorType
协议。
In Swift 2.0 NSError
conforms to the ErrorType
protocol.
对于自定义的错误,我们可以为某些情况指定关联对象,如下所示。
For a customly defined error, we can specify the associating object(s) for some cases, like below.
enum LifeError: ErrorType {
case BeBorn
case LostJob(job: String)
case GetCaughtByWife(wife: String)
...
}
我们可以舒适地执行以下操作:
We can comfortably do the following:
do {
try haveAffairWith(otherPerson)
} catch LifeError.GetCaughtByWife(let wife) {
...
}
但是,如果我们希望将其作为 NSError
传入其他位置,则会丢失它的关联对象信息。
However if we want it to pass into other places as an NSError
, it loses its associating object information.
println("\(LifeError.GetCaughtByWife("Name") as NSError)")
打印:
Error Domain=... Code=1 "The operation couldn't be completed". (... error 1)
及其 userInfo
是 nil
。
我的妻子在哪里
与 ErrorType
相关联?
推荐答案
Xcode 8中的新功能: CustomNSError
协议。
enum LifeError: CustomNSError {
case beBorn
case lostJob(job: String)
case getCaughtByWife(wife: String)
static var errorDomain: String {
return "LifeError"
}
var errorCode: Int {
switch self {
case .beBorn:
return 0
case .lostJob(_):
return 1
case .getCaughtByWife(_):
return 2
}
}
var errorUserInfo: [String : AnyObject] {
switch self {
case .beBorn:
return [:]
case .lostJob(let job):
return ["Job": job]
case .getCaughtByWife(let wife):
return ["Wife": wife]
}
}
}
这篇关于将ErrorType转换为NSError会丢失关联的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文