Channel Buffering in Swift
By default, Swift doesn't have built-in channels like Go. However, we can simulate a similar behavior using DispatchQueue and DispatchSemaphore. In this example, we'll create a buffered queue that can hold up to 2 values.
```swift
import Foundation
// Create a serial queue to ensure thread-safety
let queue = DispatchQueue(label: "com.example.bufferedQueue")
// Create a semaphore with 2 available resources
let semaphore = DispatchSemaphore(value: 2)
// Create an array to store our messages
var messages: [String] = []
// Function to send a message
func send(_ message: String) {
semaphore.wait() // Decrement semaphore count
queue.async {
messages.append(message)
print("Sent: \(message)")
}
}
// Function to receive a message
func receive() -> String? {
var result: String?
queue.sync {
if !messages.isEmpty {
result = messages.removeFirst()
semaphore.signal() // Increment semaphore count
}
}
return result
}
// Main execution
send("buffered")
send("queue")
// Receive and print messages
if let message1 = receive() {
print("Received: \(message1)")
}
if let message2 = receive() {
print("Received: \(message2)")
}
In this Swift code, we use a DispatchQueue
to ensure thread-safety when accessing our message array. The DispatchSemaphore
is used to limit the number of messages that can be sent to our buffered queue.
The send
function adds a message to the queue, waiting if the queue is full (i.e., if the semaphore count is 0). The receive
function removes and returns a message from the queue, if one is available.
To run this program, save it as BufferedQueue.swift
and use the Swift compiler:
$ swift BufferedQueue.swift
Sent: buffered
Sent: queue
Received: buffered
Received: queue
This example demonstrates how to create a buffered queue in Swift that can accept a limited number of values without a corresponding receiver for those values, similar to buffered channels in other languages.