2016-12-24 8 views
1

アプリケーション全体で使用できる完全なSwiftエラー処理と伝播システムを構築したいと思います。私は、Swiftエラー処理とエラーのメタデータ

func feedFinishedParsing(withFeedArray feedArray: [FeedItem]?, error: AnnouncerError?) { 
    // unwrap the error somewhere here 
    switch error { 
    case .networkError: 
    print("Network error occured") 
    case .parseError: 
    print("Parse error occured") 
    case .unwrapError: 
    print("Unwrap error occured") 
    default: 
    print("Unknown error occured") 
    } 
} 

しかし:

enum AnnouncerError: Error { 
    /// A network error occured 
    case networkError 
    /// The program was unable to unwrap data from nil to a non-nil value 
    case unwrapError 
    /// The parser was unable to validate the XML 
    case validationError 
    /// The parser was unable to parse the XML 
    case parseError 
} 

私は、単純なswitch文を使用して、このようなデリゲート機能にエラーの種類を取得することができます。実装は、あなたがこのような何かを持っている場合、非常に簡単ですエラーenum内の特定のケースから追​​加データを持っている、それは問題が発生したときです:

enum AnnouncerError: Error { 
    /// A network error occured 
    case networkError(description: String) //note this line 
    /// The program was unable to unwrap data from nil to a non-nil value 
    case unwrapError 
    /// The parser was unable to validate the XML 
    case validationError 
    /// The parser was unable to parse the XML 
    case parseError 
} 

がどのように私はを取得する必要があります.networkErrorのデリゲートメソッドを呼び出すと、エラータイプの文字列が返されますか?

からdescriptionを直接取得する直接的な方法がない場合は、代理メソッドにオプションの(null可能な)エラータイプがある現在のアーキテクチャを使用し続ける必要があります。エラー、または私はtry-catchシステムのような全く別のアーキテクチャを使用すべきですか?

+0

おそらく関連しています:[追加のデータを含む3つのエラー](http://stackoverflow.com/questions/41202869/swift-3-errors-with-additional-data)および[エラーのあるローカライズされた説明を提供する方法Swiftを入力しますか?](http://stackoverflow.com/questions/39176196/how-to-provide-a-localized-description-with-an-error-type-in​​-swift) –

答えて

2

descriptionのプロパティにアクセスする場合は、networkErrorのケースをあまりにも多くする必要はありません。

func feedFinishedParsing(withFeedArray feedArray: [FeedItem]?, error: AnnouncerError?) { 
    // unwrap the error somewhere here 
    switch error { 
    // Just declare description in the case, and use it if u need it. 
    case .networkError(let description): 
     print("Network error occured") 
     print(description) 
    case .parseError: 
     print("Parse error occured") 
    case .unwrapError: 
     print("Unwrap error occured") 
    default: 
     print("Unknown error occured") 
    } 
} 

もちろん、エラー処理のために堅牢なマシンを構築できますが、このプロパティにアクセスしたい場合は、上記の解決方法が役立ちます。

言語要素の高度な使い方は、Swiftです。詳しくは、Swift pattern matchingをお読みください。