2016-08-24 29 views
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語句的更好的辦法?

回答

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) 
}