如何在返回值之前等待关闭完成
How to wait for a closure completion before returning a value
如何在关闭完成后等待 return 个值。
示例:
func testmethod() -> String {
var abc = ""
/* some asynchronous service call block that sets abc to some other value */ {
abc = "xyz"
}
return abc
}
现在我希望方法仅在 xyz
值已设置为变量而非空字符串后才为 return。
如何实现?
这绝对不可能,因为这不是异步任务的工作方式。
你可以做的是这样的:
func testmethod(callback: (abc: String) -> Void) {
asyncTask() {
callback(abc: "xyz")
}
}
祝你有愉快的一天。
编辑(对于较新的 Swift 版本):
func testMethod(callback: @escaping (_ parameter: String) -> Void) {
DispatchQueue.global().async { // representative for any async task
callback("Test")
}
}
有可能(不过要确定这是你真正想要的。).
你必须使用一些东西来阻塞线程直到资源可用,比如 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.
如何在关闭完成后等待 return 个值。
示例:
func testmethod() -> String {
var abc = ""
/* some asynchronous service call block that sets abc to some other value */ {
abc = "xyz"
}
return abc
}
现在我希望方法仅在 xyz
值已设置为变量而非空字符串后才为 return。
如何实现?
这绝对不可能,因为这不是异步任务的工作方式。
你可以做的是这样的:
func testmethod(callback: (abc: String) -> Void) {
asyncTask() {
callback(abc: "xyz")
}
}
祝你有愉快的一天。
编辑(对于较新的 Swift 版本):
func testMethod(callback: @escaping (_ parameter: String) -> Void) {
DispatchQueue.global().async { // representative for any async task
callback("Test")
}
}
有可能(不过要确定这是你真正想要的。).
你必须使用一些东西来阻塞线程直到资源可用,比如 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.