Search code examples
swiftafnetworking

Cannot invoke 'async' with an argument list of type '(execute: ())'


I am trying to make a network call, then update the main thread, but it seems that any variable created in the background thread can not be sent as a parameter to the main thread:

 let task = session.dataTask(with: request as URLRequest,
                                completionHandler: {
                                    (data, response, error) in
                                    guard let _:Data=data, let _:URLResponse = response, error == nil else {


                                        return
                                    }

                                    let json = try? JSONSerialization.jsonObject(with: data!, options: [])


    var car = "hello"
    DispatchQueue.main.async (execute: self.someFunc(car)) <-- wont accept car parameter

    })

    task.resume()

here is the signature:

func someFunc( str:String) {

}

getting the following error: Cannot invoke 'async' with an argument list of type '(execute: ())'


Solution

  • The syntax

    DispatchQueue.main.async(execute: () -> Void)
    

    expects a closure without parameter.


    Use the syntax

    DispatchQueue.main.async(execute: { someFunc(str: car) })
    

    or with trailing closure syntax

    DispatchQueue.main.async {
        self.someFunc(str: car)
    }
    

    and don't forget the label parameter.