Search code examples
iosswiftasynchronousclosures

How to wait for a closure completion before returning a value


How to wait to return a value after a closure completion.

Example:

func testmethod() -> String {
   var abc = ""
   /* some asynchronous service call block that sets abc to some other value */ {
      abc = "xyz"
   }
   return abc 
}

Now I want the method to return only after xyz value has been set for variable and not empty string.

How to achieve this?


Solution

  • this is absolutely not possible, because it is just not how asynchronous tasks are working.

    what you could do is something like this:

    func testmethod(callback: (abc: String) -> Void) {
       asyncTask() {
         callback(abc: "xyz")
       }
    }
    

    Have a nice day.

    EDIT (for newer Swift Versions):

    func testMethod(callback: @escaping (_ parameter: String) -> Void) {
        DispatchQueue.global().async { // representative for any async task
            callback("Test")
        }
    }