Sean Oneal
Sean Oneal

Reputation: 45

How to convert '(Data?, URLResponse, Error?) to expected argument type '(Data?, URLResponse?, Error?) -> Void'

I don't understand why Im getting a error with { in this line. let task = URLSession

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse, error: Error?) in   //ERROR: Cannot convert value of type '(Data?, URLResponse, Error?) -> ()' to expected argument type '(Data?, URLResponse?, Error?) -> Void'

        self.removeActivityIndicator(activitiyIndicator: myActivityIndicator)

        if error != nil {
            self.displayMessage(userMessage: "Could not successfully perform this request")
            print("error=\(String(describing: error))")
            return
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

Any recommendations would be appreciated.

Upvotes: 2

Views: 674

Answers (1)

vadian
vadian

Reputation: 285150

Please read the error carefully, it says that the second closure parameter (URLResponse) must be optional (URLResponse?)

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

However to annotate the parameter types is not necessary

let task = URLSession.shared.dataTask(with: request) { data, response, error in

The compiler will complain if you treat the (optional) types wrongly.

And don't use NS.. collection types in Swift. Use native types.

Upvotes: 2

Related Questions