I want to be able to call multiple void functions in parallel.
How do you call a let async on a void functions?
for functions that return an item its easy
async let games = getGames()
func getGames() async -> Games {
...
}
I want to be able to call multiple void functions in parallel.
How do you call a let async on a void functions?
for functions that return an item its easy
async let games = getGames()
func getGames() async -> Games {
...
}
Would this work? I'm not really sure what you're after.
for _ in 0 ..< taskCount {
Task { await voidFunc() }
}
@Avi that spawns off unstructured tasks without ever awaiting on them -- don't do that unless you have strong reasons to.
Regarding the async let
question, you can absolutely async let x: Void = ...
and await it later on _ = await x
.
Even with a property, you need explicit : Void
to silence a warning, but I'm not finding that you need _ =
.
var void: Void {
get async { }
}
func ƒ() async {
async let void: Void = void
await void
}
There is a related bug filed here:
Swift's Task Groups that were introduced in Swift 5.5 will let you do what you want. A task group lets you run a series of async tasks in parallel, and await on all of them returning, with the proviso that they all have to return the same type. That type can be the type Void.self
, so this is applicable for what you're looking for.
Donny Wals has a good fully-explained set of examples that specifically discusses the case of void functions like you're looking for. The core syntax to use a task group with a series of void functions could be:
await withTaskGroup(of: Void.self) { group in
group.addTask {
await myFirstVoidFunction()
}
group.addTask {
await mySecondVoidFunction()
}
group.addTask {
await myThirdVoidFunction()
}
}
As Donny notes in his blog post:
As soon as a task is added to the task group it will [begin] running concurrently with any other tasks that [you] may have already added to the group.
His example also shows how you might iterate over list items or similar to add tasks to a task group.
It would be great to have something akin to async let
as that is even more simple to set up, but this is an option available today.
Task groups are great, but definitely a lot noisier for things like this. I think we can afford to improve the ergonomics around async let
for spinning up a few "fire-and-forget" tasks into the void.
We should remove this warning for async let
.