I found this other thread that is exactly what I am asking:
But that refs Swift 5.5, and we have 6 now, 3 years later. Also, the code answers are so terse readers have to fill in code in their head, which increases cognitive load on those trying to solves problems. Well, the withTaskGroup
answer is full enough but that has a problem I will talk about in a moment.
So moving on...
We have the following scenario:
- Run 3 async funcs in parallel
- The funcs for not return a value
- Do a thing when all 3 are done
Someone coded it like this by using async-let
and throwing away the variables.
async let unused1: () = ring.ding1()
async let unused2: () = ring.ding2()
async let unused3: () = ring.ding3()
_ = await (unused1, unused2, unused3) // Parallel.
print("test2: Do this after.")
I incorrectly thought that the equivalent for funcs that return void would be:
_ = await( // Serial.
ring.ding1(),
ring.ding2(),
ring.ding3()
)
print("test3: Do this after.")
But the funcs are run serially in the above example.
So, one correct answer I figured out is:
let h1 = Task { await ring.ding1() }
let h2 = Task { await ring.ding2() }
let h3 = Task { await ring.ding3() }
_ = await(h1.result, h2.result, h3.result) // Parallel.
print("test1: Do this after.")
But that does not have the nice syntactic sugar of async-let. However, yes, it is more concise than Foundation dispatch groups, and certainly less bug prone.
However, it is noisier than async-let for a thing that is simpler – a func call with no return value has busier syntax than a func call with a return value. And that is my problem with withTaskGroup
for our scenario, it is noisier still. It seems built for something more heavyweight.
So, I am writing this post because I am mystified and in disbelief that a language designer could create something so elegant as async-let and yet not have something similar for a simpler subset of the same situation. My hope is that someone posts an answer that embarrasses me in its obviousness that I missed it.
Side note: if it turns out there is no conciser syntax, I prefer the original code of using throwaway vars in async-let.