Search code examples
swiftfunctionasynchronousparameter-passingdispatch-queue

How to pass a parameter to a block executed asynchronously in Swift?


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?


Solution

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