Swift Calling Async Function Without A Return Value
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.
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.
Related Questions
- → How to write this recursive function in Swift?
- → Send email from a separated file using Swift Mailer
- → Laravel Mail Queue: change transport on fly
- → "TypeError: undefined is not an object" when calling JS function from Swift in tvOS app
- → Are Global/Nested functions in JavaScript implemented as closures?
- → JavascriptCore: executing a javascript-defined callback function from native code
- → Swift SHA1 function without HMAC
- → Shopify GraphQL using swift not getting response
- → How to disconnect git for a project in intellij?
- → Sending a request to a php web service from iOS
- → Add only objects that don't currently exist to Realm database
- → How to sort using Realm?
- → Realm object as member is nil after saving