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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With