This content originally appeared on DEV Community and was authored by Harsh Prajapat
Here’s a simple and clean implementation of a Stack using an Array in Swift, including basic operations:
struct Stack<T> {
private var elements: [T] = []
// Push an element onto the stack
mutating func push(_ value: T) {
elements.append(value)
}
// Pop an element from the top of the stack
mutating func pop() -> T? {
return elements.popLast()
}
// Peek at the top element without removing it
func peek() -> T? {
return elements.last
}
// Check if the stack is empty
func isEmpty() -> Bool {
return elements.isEmpty
}
// Get the current size of the stack
func size() -> Int {
return elements.count
}
}
🧪 Example Usage:
var stack = Stack<Int>()
stack.push(10)
stack.push(20)
stack.push(30)
print(stack.peek() ?? "Empty") // Output: 30
print(stack.pop() ?? "Empty") // Output: 30
print(stack.size()) // Output: 2
print(stack.isEmpty()) // Output: false
stack.pop()
stack.pop()
print(stack.isEmpty()) // Output: true
This content originally appeared on DEV Community and was authored by Harsh Prajapat