英文:
How to pass a parameter to a block executed asynchronously in Swift?
问题
除了function dispatch_async
,该函数用于提交一个块以异步执行,iOS还提供了另一个function dispatch_async_f
,用于提交一个带有单个参数的函数以异步执行。
在Swift中,我可以调用dispatch_async
,如DispatchQueue.global().async {}
,但我没有找到任何调用dispatch_async_f
的方法。
那么,我如何将参数传递给异步执行的块?
英文:
In addition to function dispatch_async
, that submits a block for asynchronous execution, iOS provides another function dispatch_async_f
to submit a function with a single parameter for asynchronous execution.
in Swift, I can call dispatch_async
as DispatchQueue.global().async {}
, but I did not find any way to call dispatch_async_f
.
So, how do I pass a parameter to a block executed asynchronously?
答案1
得分: 1
dispatch_async_f()
可以在没有块或闭包的C代码中使用。
在Swift中,您只需传递一个闭包,闭包调用该函数:
DispatchQueue.global().async {
let theParameter = ...
theFunction(theParameter)
}
闭包还可以在创建时捕获值:
let theParameter = ...
DispatchQueue.global().async {
theFunction(theParameter)
}
英文:
dispatch_async_f()
can be used in C code, which has no blocks or closures.
In Swift you simply pass a closure, and the closure calls the function:
DispatchQueue.global().async {
let theParameter = ...
theFunction(theParameter)
}
The closure can also capture values when created:
let theParameter = ...
DispatchQueue.global().async {
theFunction(theParameter)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论