Our first example demonstrates how to use a dispatch group to wait for multiple asynchronous tasks to complete. This is similar to the concept of wait groups in other languages.
To run the program, save it as DispatchGroups.swift and use swift to compile and run:
The order of workers starting up and finishing is likely to be different for each invocation.
In this Swift version:
We use DispatchGroup instead of WaitGroup.
group.enter() is equivalent to wg.Add(1).
group.leave() is equivalent to wg.Done().
group.wait() is equivalent to wg.Wait().
We use DispatchQueue.global().async to create and run tasks asynchronously, which is similar to using goroutines in Go.
Swift’s concurrency model is different from Go’s, but this example demonstrates how to achieve similar functionality using Grand Central Dispatch (GCD), which is Swift’s native concurrency framework.