How to implement Stack in Swift

A stack is a last-in-first-out (LIFO) collection, which means the last thing we pushed is the first thing that gets popped off.

If you used UINavigationController before, probably you used the method pushViewController(_:animated:) to push a view controller onto the navigation stack, and then used method popViewController(animated:) to pop the view controller off the navigation stack.

As you know there is no built-in Stack in Swift, so let's implement one.

class Stack<T> {
    var items: [T] = []

    var isEmpty: Bool {
        return items.isEmpty

    var count: Int {
        return items.count

    func push(_ item: T) {

    func pop() -> T {
        return items.removeLast()

    func peek() -> T? {
        return items.last

We just use the generic array as a backing store. And append or remove the element at the end of the array.

Finally let's test the Stack.

let stack = Stack<Int>()

while !stack.isEmpty {
// it would print 3 2 1 in the console

Here are some other posts regarding iOS and Swift:

Hope this helps,

DigitalOcean Referral Badge