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) {
        items.append(item)
    }

    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>()
stack.push(1)
stack.push(2)
stack.push(3)

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

Here are some other posts regarding iOS and Swift:

Hope this helps,
Michael

DigitalOcean Referral Badge