How to implement a stack using an array in Swift

1 Answer

0 votes
var stack: [String] = []

// Push elements onto the stack
stack.append("Swift")
stack.append("Python")
stack.append("Java")
stack.append("C")

print("Stack after pushes: \(stack)")

// Peek at the top element
if let top = stack.last {
    print("Top of stack: \(top)")
}

// Pop elements off the stack
while !stack.isEmpty {
    let popped = stack.removeLast()
    print("Popped: \(popped) | Remaining stack: \(stack)")
}


print("Stack after pop: \(stack)")



/*
run:

Stack after pushes: ["Swift", "Python", "Java", "C"]
Top of stack: C
Popped: C | Remaining stack: ["Swift", "Python", "Java"]
Popped: Java | Remaining stack: ["Swift", "Python"]
Popped: Python | Remaining stack: ["Swift"]
Popped: Swift | Remaining stack: []
Stack after pop: []

*/

 



answered Aug 16, 2025 by avibootz
...