Select in Swift
This Swift code demonstrates a similar concept to the original example, using Grand Central Dispatch (GCD) to manage concurrent operations.
In this example, we use DispatchQueue
instead of channels. Each queue represents a concurrent operation that will complete after a specified delay.
We create two queues, c1
and c2
, each of which will execute a block of code after a delay (1 second and 2 seconds respectively).
To wait for both operations to complete, we use a DispatchGroup
. We enter the group before each operation and leave it when the operation completes. The group.wait()
call at the end ensures that we don’t exit the program until both operations have finished.
When you run this program, you’ll see:
Note that the total execution time is only ~2 seconds since both the 1 and 2 second delays execute concurrently.
While Swift doesn’t have a direct equivalent to Go’s select
statement for channels, this approach using GCD provides similar functionality for managing concurrent operations.