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:
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.