如何在关闭完成后等待返回值。
例子:
func testmethod() -> String {
var abc = ""
/* some asynchronous service call block that sets abc to some other value */ {
abc = "xyz"
}
return abc
}
现在我希望该方法仅在为变量而非空字符串设置了 xyz
值后返回。
如何实现?
最佳答案
这是可能的 (但是请确保这是您真正想要的。)。
您必须使用一些东西来阻塞线程直到资源可用,例如信号量。
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.
关于ios - 如何在返回值之前等待关闭完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31221966/