gpt4 book ai didi

swift - 如何从 catch 子句中的 NSError 获取 userInfo

转载 作者:搜寻专家 更新时间:2023-10-30 21:59:32 24 4
gpt4 key购买 nike

如果我有一个 throw 方法,像这样:

func doSomethingWithString(string:String) throws {
guard string.characters.count > 0 else {
throw NSError(domain: "CustomErrorDomain", code: 42, userInfo: ["foo" : "bar"])
}
// Do something with string...
}

然后我尝试调用它并读取userInfo:

do {
try doSomethingWithString("")
} catch let error as NSError {
print(error.domain)
print(error.code)
print(error.userInfo)
}

...它作为空字典返回,(但域和代码已正确填充):

CustomErrorDomain
42
[:]

但是如果我添加这个额外的步骤:

do {
try doSomethingWithString("")
} catch let e {
let error = e as NSError
print(error.domain)
print(error.code)
print(error.userInfo)
}

...有效:

CustomErrorDomain
42
[foo: bar]

有人知道为什么会这样吗?

仅供引用 - 我正在使用 Xcode 7 beta 2 (7A121l)

最佳答案

这是一个错误,已在 Xcode 7 Beta 4 中修复。以下是发行说明(PDF,第 15 页)的摘录:

Resolved Issues in Xcode 7 beta 4 — Swift 2.0 and Objective-C

When throwing a reference to an NSError instance in Swift, the Swift runtime no longer loses the userInfo of the original NSError if it is caught as an NSError. The Swift runtime now preserves the identity of the original NSError. For example, this assertion now holds:

 let e = NSError(...)
do {
throw e
} catch let e2 as NSError {
assert(e === e2)
}

关于swift - 如何从 catch 子句中的 NSError 获取 userInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31201930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com