加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 将ErrorType转换为NSError会丢失关联的对象

发布时间:2020-12-14 06:08:37 所属栏目:百科 来源:网络整理
导读:在Swift 2.0中NSError符合ErrorType协议。 对于自定义的错误,我们可以为某些情况指定关联对象,如下所示。 enum LifeError: ErrorType { case BeBorn case LostJob(job: String) case GetCaughtByWife(wife: String) ...} 我们可以舒适地做以下事情: do {
在Swift 2.0中NSError符合ErrorType协议。

对于自定义的错误,我们可以为某些情况指定关联对象,如下所示。

enum LifeError: ErrorType {
    case BeBorn
    case LostJob(job: String)
    case GetCaughtByWife(wife: String)
    ...
}

我们可以舒适地做以下事情:

do {
    try haveAffairWith(otherPerson)
} catch LifeError.GetCaughtByWife(let wife) {
    ...
}

然而,如果我们想要它作为NSError传递到其他地方,它会丢失其关联对象信息。

println("(LifeError.GetCaughtByWife("Name") as NSError)")

打印:

Error Domain=... Code=1 "The operation couldn't be completed". (... error 1)

并且其userInfo为nil。

我的妻子在哪里与ErrorType关联?

Xcode 8中的新功能:CustomNSError protocol。
enum LifeError: Error,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]
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读