Swift 2:错误处理:throw:如何传递带有错误的对象?

时间:2015-07-22 09:37:36

标签: swift error-handling swift2

如何在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)
}

1 个答案:

答案 0 :(得分: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              
}