How do I implement a generic deque in Swift?

In Swift, you can implement a generic deque (double-ended queue) that allows you to efficiently add and remove elements from both ends of the collection. This data structure is useful when you need fast access and manipulation of elements at both ends.

class Deque { private var items: [Element] = [] var count: Int { return items.count } var isEmpty: Bool { return items.isEmpty } func pushFront(_ element: Element) { items.insert(element, at: 0) } func pushBack(_ element: Element) { items.append(element) } func popFront() -> Element? { return isEmpty ? nil : items.removeFirst() } func popBack() -> Element? { return isEmpty ? nil : items.removeLast() } func peekFront() -> Element? { return items.first } func peekBack() -> Element? { return items.last } } // Example Usage: let deque = Deque() deque.pushBack(1) deque.pushBack(2) deque.pushFront(0) print(deque.popFront()!) // Outputs: 0 print(deque.popBack()!) // Outputs: 2 print(deque.peekFront()!) // Outputs: 1 print(deque.peekBack()!) // Outputs: 1

generic deque swift deque implementation double-ended queue swift programming