2
我使用的是一個繼承自Error
(或ErrorType
在Swift 2中)的枚舉,我試圖以這樣的方式使用它,以便我可以捕獲錯誤並使用類似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)
}
是否有印刷錯誤的描述,而不必檢查每一個類型的UpdateError
發生在catch語句的更好的辦法?