2017-02-13 64 views
-5

我得到這個錯誤傳遞可選:斯威夫特3:致命錯誤:意外發現零而展開的可選值

fatal error: unexpectedly found nil while unwrapping an Optional value 

這裏是我的代碼:

func makeRequestcompletion(completion:@escaping (_ response:Data, _ error:NSError)->Void) { 
    let urlString = URL(string: "https://myUrl.com") 
    if let url = urlString { 
     let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, urlRequestResponse, error) in 

      completion((data)!, error as! NSError) // <-- here is where I'm getting the error 
     }) 
    task.resume() 
    } 
} 

任何你知道這是爲什麼我收到這個錯誤?

我真的很感謝你的幫助。

+5

的可能的複製[什麼是「致命的錯誤:零而展開的可選值意外地發現」呢?(http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly -found-nil-while-unwrapping-an-optional-valu) – Hamish

+0

@Hamish,不,因爲我不問什麼是可選的。我在問爲什麼數據出現錯誤,即使當我解開變量時 – user2924482

+0

無關你爲什麼將'error'轉換爲'NSError'?只需使用'Error'。 – rmaddy

回答

0

將您的閉包參數更改爲可選,以便您不必強制拆包。

func makeRequestcompletion(completion: @escaping (_ response:Data?, _ error:Error?)->Void) 
{ 
    let urlString = URL(string: "http://www.myUrl.com") 
    if let url = urlString { 
    let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, urlRequestResponse, error) in 
     completion(data, error) // <-- here is I'm getting the error 
     }) 
     task.resume() 
    } 

} 
+1

這項工作!感謝您的幫助! – user2924482

相關問題