How do I implement a generic stack in Swift?

A generic stack in Swift allows you to create a collection that adheres to the Last In, First Out (LIFO) principle. Below is an example of how to implement a generic stack using Swift's powerful type system.

// Define a generic Stack structure struct Stack { private var items: [Element] = [] // Push an item onto the stack mutating func push(_ item: Element) { items.append(item) } // Pop an item off the stack mutating func pop() -> Element? { return items.isEmpty ? nil : items.removeLast() } // Peek at the top item of the stack without removing it func peek() -> Element? { return items.last } // Check if the stack is empty var isEmpty: Bool { return items.isEmpty } // Get the count of items in the stack var count: Int { return items.count } } // Example usage: var intStack = Stack() intStack.push(1) intStack.push(2) intStack.push(3) print(intStack.pop()!) // Output: 3 print(intStack.peek()!) // Output: 2 print(intStack.isEmpty) // Output: false print(intStack.count) // Output: 2

Generic Stack Swift LIFO Stack Implementation Swift Generics