2017-04-08 105 views
0

我有一個協議,其中包含兩個功能successWeathererrorWeather。當狀態代碼返回200-299以外的內容時,我希望它拋出errorWeather函數。警告聲明中強制錯誤?

我的問題是:如果警衛獲得狀態碼,我該如何強制執行錯誤?截至目前,錯誤返回零。

func errorWeather(error: NSError)

let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in 
     if let error = error { 
      self.delegate.errorWeather(error: error as! NSError) 
     } 

     guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else { 
      print("Your request returned a status code other than 2xx!") 
      //How can I force an error? 
      return 
     } 
+0

這是有點不清楚 - 至少對我來說,協議和throwable函數之間的關係是什麼?你能詳細說明一下嗎? –

+0

我基本上創建它作爲使用API​​的代表系統。在detailView中它符合協議,並且必須使用successWeather和errorWeather。 @AhmadF – Casey

+0

所以,如果我知道了 - 實現delegate和throwable函數的目的是什麼?我建議讓它只是一個選項來處理錯誤。是你應該如何實現委託或throwable函數的問題?此外,您可能需要檢查[本問答](http://stackoverflow.com/questions/40501780/examples-of-delegates-in-swift-3/40503024#40503024)。 –

回答

1

一個NSError對象封裝有關的可延伸的,面向對象的方式的錯誤狀態的信息。它由預定義的錯誤域,域特定的錯誤代碼和包含特定於應用程序的信息的用戶信息字典組成。更多檢查Apple Doc

guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else { 
       print("Your request returned a status code other than 2xx!") 
       //How can I force an error? 
       let error = NSError(domain: "statusCode", 
           code: (response as? HTTPURLResponse)?.statusCode, 
          userInfo: [NSLocalizedDescriptionKey: "Your request returned a status code other than 2xx!"]) 

        self.delegate.errorWeather(error: error) 
       return 
      } 
+1

太棒了!這正是我所期待的。感謝您鏈接文檔! – Casey

+1

這是我的伴侶 –