我正在使用一个从Error
(或Swift 2中的ErrorType
)继承的枚举,并且我试图以这样一种方式使用它:我可以捕获错误并使用类似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
类型:
do {
try functionThatThrowsUpdateError()
} catch {
NSLog((error as! UpdateError).description)
}
有没有一种更好的方法来打印错误描述,而不必检查catch语句中出现的每种类型的UpdateError
?
发布于 2016-08-24 04:16:25
您可以定义另一个(可能是空的)协议,并使您的错误符合该协议。
protocol DescriptiveError {
var description : String { get }
}
// specify the DescriptiveError protocol in each enum
然后,您可以根据协议类型进行模式匹配。
do {
try functionThatThrowsUpdateError()
} catch let error as DescriptiveError {
print(error.description)
}
https://stackoverflow.com/questions/39112635
复制