【问题标题】:Swift 2: Error handling: throw: How to pass an object with an error?Swift 2:错误处理:抛出:如何传递有错误的对象?
【发布时间】:2025-12-03 08:15:01
【问题描述】:

在 Swift2 中抛出错误时如何传递 userInfo 引用对象?

这样的东西会很好:

guard let refIDString = memberXMLElement.attributes["ref"] else {
     throw OSMVectorMapDescriptionError.ElementDoesntContainRequiredAttributes(userInfo:memberXMLElement)
}

然后:

catch OSMVectorMapDescriptionError.ElementDoesntContainRequiredAttributes {
  (userInfo:AnyObject) in
      //do stuff                 
 }

但是错误是枚举,我们可以像这里一样指定,但是如何捕获呢?

public enum OSMVectorMapDescriptionError:ErrorType {
    case ElementDoesntContainRequiredAttributes(userInfo:AnyObject)
}

【问题讨论】:

  • 另外别忘了你也可以throw老好NSError。您可以通过catch let e as NSError 捕获它,然后您可以通过e.userInfo 访问用户信息(此问题已在 Xcode 7 beta 4 中修复,在以前的版本中不起作用)。

标签: swift error-handling swift2


【解决方案1】:

假设你不需要someLevel,你可以定义

public enum OSMVectorMapDescriptionError:ErrorType {
   case ElementDoesntContainRequiredAttributes(userInfo: ...)
}

保持不变

guard let refIDString = memberXMLElement.attributes["ref"] else {
    throw OSMVectorMapDescriptionError.
              ElementDoesntContainRequiredAttributes(userInfo:memberXMLElement)
}

catch OSMVectorMapDescriptionError.
          ElementDoesntContainRequiredAttributes(let userInfo) {
  //do stuff using userInfo              
}

【讨论】:

    最近更新 更多