尝试打印错误(AKA ErrorType)枚举的描述

时间:2016-08-24 00:24:52

标签: ios swift error-handling enums

我正在使用一个继承自Error(或Swift 2中的ErrorType)的枚举,我试图以这样的方式使用它,以便我可以捕获错误并使用像{{{{{ 1}}打印错误的描述。

这就是我的错误枚举:

print(error.description)

需要注意的一点是,enum UpdateError: Error { case NoResults case UpdateInProgress case NoSubredditsEnabled case SetWallpaperError var description: String { switch self { case .NoResults: return "No results were found with the current size & aspect ratio constraints." case .UpdateInProgress: return "A wallpaper update was already in progress." case .NoSubredditsEnabled: return "No subreddits are enabled." case .SetWallpaperError: return "There was an error setting the wallpaper." } } // One of many nested enums enum JsonDownloadError: Error { case TimedOut case Offline case Unknown var description: String { switch self { case .TimedOut: return "The request for Reddit JSON data timed out." case .Offline: return "The request for Reddit JSON data failed because the network is offline." case .Unknown: return "The request for Reddit JSON data failed for an unknown reason." } } } // ... } 中有一些嵌套枚举,所以这样的东西不起作用,因为嵌套的枚举本身不属于UpdateError类型:

UpdateError

是否有更好的方法来打印错误描述,而无需检查catch语句中出现的每种类型的do { try functionThatThrowsUpdateError() } catch { NSLog((error as! UpdateError).description) }

1 个答案:

答案 0 :(得分:3)

您可以定义另一个(可能是空的)协议,并将错误符合它。

protocol DescriptiveError {
   var description : String { get }
}

// specify the DescriptiveError protocol in each enum

然后,您可以根据协议类型进行模式匹配。

do {
  try functionThatThrowsUpdateError()
} catch let error as DescriptiveError {
  print(error.description)
}