2016-08-24 2 views
2

Error (또는 Swift 2의 ErrorType)에서 상속하는 열거 형을 사용하고 있으며 오류 및 오류를 잡아낼 수있는 방식으로 사용하려고합니다. print(error.description)과 같은 것을 사용하여 오류에 대한 설명을 인쇄하십시오. 중첩 된 열거 형이 아니기 때문에오류 (일명 오류 유형) 열거 형의 설명 인쇄 시도

UpdateError 내에서 몇 가지 중첩 된 열거가 너무 이런 식으로 뭔가가 작동하지 않습니다
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의 자신을 입력 : catch 문에서 발생 UpdateError의 모든 유형을 확인하지 않고 오류에 대한 설명을 인쇄하는 더 좋은 방법은

do { 
    try functionThatThrowsUpdateError() 
} catch { 
    NSLog((error as! UpdateError).description) 
} 

있습니까?

답변

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