我有一个函数我们称之为“a”,它运行一些代码然后返回一个字符串“x”在异步代码块中更新然后返回。
我该如何让程序等待异步代码运行后再返回 x?
func a() -> String {
//code
//code
var x: String
async block {
x = "test"
}
return x
}
最佳答案
就像每个人指出的那样,您可以使用完成处理程序(closure
)来执行操作。但您也可以使用 DispatchSemaphore
等待异步调用完成。信号量在调用 wait
时获得锁定,并在从异步 block 发出信号时释放。
func a()->String{
var x = ""
let semaphore = DispatchSemaphore(value: 0)
DispatchQueue.main.async {
x = "test"
semaphore.signal()
}
semaphore.wait()
return x
}
关于swift - 在继续之前等待异步 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44512090/