Data Structure - Coding a Stack in Swift

After covering last week how to code a Queue in Swift, it sounds natural to move on to the Stack, another really handy data structure which also find his place in iOS development. Let’s see why.

Concept

Similar to a Queue, a Stack execute operation in a linear order, however the ordered is reversed to what would be with a Queue. The last element inserted would be the first one treated before moving to the next one. This specific order is called LIFO (Last in, First out).

stack-data-structure

A Stack has also its own functions and properties:

  • a way to push element: to add a new element to the stack
  • a way to pop element: to remove the latest element pushed, at top of the stack.
  • a peek or top: the element at the top of the stack

Let’s see how to implement this in Swift.

Implementation

class Stack<T> {

  private var elements: [T] = []

  func push(_ element: T) {
    elements.append(element)
  }

  func pop() -> T? {
    guard !elements.isEmpty else {
      return nil
    }
    return elements.popLast()
  }

  var top: T? {
    return elements.last
  }
}

Here is an example. Assuming we have a cookie jar, the first one added in in would be the last one to be eaten.

let cookieJar = Stack<String>()
cookieJar.push("chocolate")
cookieJar.push("almond")
cookieJar.push("peanut butter")

// when getting one to eat
cookieJar.pop() // eating "peanut butter" cookie
cookieJar.top // next to be eaten "almond"

Regarding the performance, each function and property of a Stack operates in O(1) time and space, there is no iteration through each of them.

So far so good, but where in iOS development we are using it without noticing? Let’s see concrete usage.

Usage

The first example I have that uses a stack system in iOS is UINavigationController. When we push a new UIViewController, it got added to the stack navigation, stays at the top the UI layer and eventually got removed when user navigates back and pop it. That’s exactly what we describe above.

So if we want to re-implement our own navigation system, let say using Coordinator pattern for instance, we could use a Stack data structure to support it.

Another example is how keyboard works. When we press each key, it’s equivalent to pushing a new character into the stack of the text field. The same way, when we press “delete” key, it pops the last character added to be cleared from the stack.

From those two examples, we can see that using a Stack can be an easy way to go backward to any operations given, which makes it quite good for history features.

At the end we saw different practical use-cases where a Stack can be used in iOS development and how to implement a generic one.

Happy coding

© 2023 Benoit Pasquier. All Rights Reserved
Author's picture

Benoit Pasquier

Software Engineer πŸ‡«πŸ‡·, writing about career development, mobile engineering and self-improvement

ShopBack πŸ’°

Singapore πŸ‡ΈπŸ‡¬