3

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.

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

9

Swift implicitly returns Void for non-returning function, so I guess this would be fine

func do() async {
  something()
}
async let foo: Void = do() // just explicit Void so the compiler doesn't emit a warning telling you that may not be expected

//do other stuff
stuff()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.