-3

I'm getting this error passing optional:

fatal error: unexpectedly found nil while unwrapping an Optional value

Here is my code:

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

Any of you knows why I'm getting this error?

I'll really appreciate your help.

Hamish
  • 78,605
  • 19
  • 187
  • 280
user2924482
  • 8,380
  • 23
  • 89
  • 173
  • 5
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Hamish Feb 13 '17 at 23:36
  • @Hamish, no because I'm not asking what is an optional. I'm asking why of the error with data even when I'm unwrapping the variable – user2924482 Feb 13 '17 at 23:42
  • Unrelated by why are you casting `error` to `NSError`? Just use `Error`. – rmaddy Feb 13 '17 at 23:43
  • 1
    @user2924482 Yes, it is a duplicate. Please read the answers to that question. It explains why you get the error and how to avoid the error. – rmaddy Feb 13 '17 at 23:43
  • @user2924482 But the problem is you're *force unwrapping* `data`. If it is `nil`, you crash. The linked Q&A explains both this and shows various safe ways to unwrap optionals. – Hamish Feb 13 '17 at 23:44

1 Answers1

2

Change your closure parameters to optional so that you don't have to force unwrap it.

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

}
Christian Abella
  • 5,747
  • 2
  • 30
  • 42