Select in Swift

import Foundation

// For our example we'll select across two channels.
let c1 = DispatchQueue(label: "Channel 1")
let c2 = DispatchQueue(label: "Channel 2")

// Each queue will execute a block after some amount
// of time, to simulate e.g. blocking operations
// executing concurrently.
c1.asyncAfter(deadline: .now() + 1) {
    print("received one")
}

c2.asyncAfter(deadline: .now() + 2) {
    print("received two")
}

// We'll use a DispatchGroup to await both of these values
// simultaneously, printing each one as it arrives.
let group = DispatchGroup()

group.enter()
c1.notify(queue: .main) {
    group.leave()
}

group.enter()
c2.notify(queue: .main) {
    group.leave()
}

group.wait()

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:

received one
received two

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.