Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 845
Arsh Aulakh Avatar asked Jul 04 '15 14:07

Arsh Aulakh


1 Answers

It is possible (However make sure this is what you really want.).

You have to use something that will block a thread until a resource is available, like semaphores.

var foo: String {
    let semaphore = DispatchSemaphore(value: 0)
    var string = ""

    getSomethingAsynchronously { something in
        string = something
        semaphore.signal()
    }

    semaphore.wait()
    return string
}

Bare in mind that the thread you are working on will be blocked until the getSomethingAsynchronously is done.

like image 175
Jakub Truhlář Avatar answered Oct 13 '22 00:10

Jakub Truhlář