如何在Swift中将参数传递给异步执行的块?

huangapple go评论83阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2020年1月6日 18:30:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定