Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何在catch子句中从NSError获取userInfo_Swift_Error Handling_Swift2 - Fatal编程技术网

Swift 如何在catch子句中从NSError获取userInfo

Swift 如何在catch子句中从NSError获取userInfo,swift,error-handling,swift2,Swift,Error Handling,Swift2,如果我有投掷法,比如: func doSomethingWithString(string:String) throws { guard string.characters.count > 0 else { throw NSError(domain: "CustomErrorDomain", code: 42, userInfo: ["foo" : "bar"]) } // Do something with string... } 然后我尝试调用它并阅读userIn

如果我有投掷法,比如:

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)
}
。。。它返回为空字典(但域和代码已正确填充):

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

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)

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

解决了Xcode 7 beta 4-Swift 2.0和Objective-C中的问题

什么时候 在Swift中引发对NSError实例的引用,Swift 运行时不再丢失原始NSError的userInfo(如果是) 作为一个错误被抓住。Swift运行时现在保留 原始N错误。例如,此断言现在适用于:


非常有趣。。。不知道为什么会发生这种情况,我认为这是一个bug,请在BuGrPut.Apple。我现在已经申请了一个雷达。这一个是在Xcode 7 Beta 4中修复的。现在可以工作了。
CustomErrorDomain
42
[foo: bar]
 let e = NSError(...)
 do {
   throw e
 } catch let e2 as NSError {
   assert(e === e2)
 }