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

Swift 2: Error handling: throw: How to pass an object with an error?

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

假设你不需要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              
}