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
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?