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

How to get userInfo from NSError in catch clause

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

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)
 }