Ad

Swift Calling Async Function Without A Return Value

- 1 answer

Is there anyway in swift's new structured concurrency model to do the following without a dummy bool return?

func do() async -> Bool {
  something()
  return true
}
async let foo = do()

//do other stuff
stuff()

//now I need to know that "do" has finished
await foo

I know that I can do the following but it will not run concurrently:

func do() async {
  something()
}
await do()
stuff()

//cannot run "stuff" and "do" concurrently

I feel like I am missing a basic idea here because the top block of code does what I need but feels like a hack due to the Bool return.

Ad

Answer

What you're describing is a Task. For example:

Task { await `do`() }
stuff()

This will run do() concurrently with stuff(). If you need to keep track of when do() completes, you can await the task's value:

let task = Task { await `do`() }
stuff()
await task.value // Doesn't actually return anything, but will block

This kind of Task runs in the context of the current Actor, which is usually what you want. If you want something independent of the current Actor, you can use Task.detached() instead.

If you've previously used DispatchQueues, in many of the places you would have written queue.async { ... }, you can now write Task { ... }. The new system is much more powerful, but it maps fairly nicely to the old system if you want it to.

Ad
source: stackoverflow.com
Ad