How do I implement a generic queue in Swift?

In Swift, you can implement a generic queue using a class or struct that uses an array to store the elements. The generic type allows the queue to store any data type, making it versatile. Below is an example of how to implement a simple generic queue in Swift.

class Queue { private var elements: [T] = [] func enqueue(_ element: T) { elements.append(element) } func dequeue() -> T? { guard !elements.isEmpty else { return nil } return elements.removeFirst() } func peek() -> T? { return elements.first } var isEmpty: Bool { return elements.isEmpty } var count: Int { return elements.count } } // Example usage: let integerQueue = Queue() integerQueue.enqueue(1) integerQueue.enqueue(2) print(integerQueue.dequeue() ?? "Queue is empty") // Outputs 1

Generic Queue Swift Queue Implementation Swift Generics Data Structure in Swift