Swift错误处理和错误元数据

Swift错误处理和错误元数据,swift,swift3,Swift,Swift3,我想构建一个完全快速的错误处理和传播系统,可以在整个应用程序中使用。如果您有以下内容,则实现相当简单: enum AnnouncerError: Error { /// A network error occured case networkError /// The program was unable to unwrap data from nil to a non-nil value case unwrapError /// The parser was unable

我想构建一个完全快速的错误处理和传播系统,可以在整个应用程序中使用。如果您有以下内容,则实现相当简单:

enum AnnouncerError: Error {
  /// A network error occured
  case networkError
  /// The program was unable to unwrap data from nil to a non-nil value
  case unwrapError
  /// The parser was unable to validate the XML
  case validationError
  /// The parser was unable to parse the XML
  case parseError
}
我可以使用一个简单的switch语句获得委托函数中的错误类型:

func feedFinishedParsing(withFeedArray feedArray: [FeedItem]?, error: AnnouncerError?) {
  // unwrap the error somewhere here
  switch error {
  case .networkError:
    print("Network error occured")
  case .parseError:
    print("Parse error occured")
  case .unwrapError:
    print("Unwrap error occured")
  default:
    print("Unknown error occured")
  }
}
但是,我在错误
enum
中有一个特定案例的附加数据,这就是问题出现的时候:

enum AnnouncerError: Error {
  /// A network error occured
  case networkError(description: String) //note this line
  /// The program was unable to unwrap data from nil to a non-nil value
  case unwrapError
  /// The parser was unable to validate the XML
  case validationError
  /// The parser was unable to parse the XML
  case parseError
}
如果我使用
.networkError
调用委托方法,如何从错误类型中获取
说明
字符串


作为扩展,如果无法直接从
.networkError
获取
说明
,我是否应继续使用当前体系结构,其中委托方法具有可选(可为空)错误类型,以便检查错误类型,或者我应该使用一个完全不同的体系结构,比如try-catch系统,如果是,我应该如何实现它

如果要访问
networkError
案例的
description
属性,无需执行太多操作

func feedFinishedParsing(withFeedArray feedArray: [FeedItem]?, error: AnnouncerError?) {
    // unwrap the error somewhere here
    switch error {
    // Just declare description in the case, and use it if u need it.
    case .networkError(let description):
        print("Network error occured")
        print(description)
    case .parseError:
        print("Parse error occured")
    case .unwrapError:
        print("Unwrap error occured")
    default:
        print("Unknown error occured")
    }
}
当然,您可以为错误处理构建一个健壮的机器,但是如果您只想访问这个属性,上面的解决方案就可以了

无论如何,我建议进一步阅读,详细解释
开关
语言元素的高级用法的内容是
Swift

可能相关的:和。