Building a generic Swift Stack

Let's build a basic Stack data structure with Swift. We will have to cover a couple of core concepts: Generics in Swift, and Basic Stack operations. Let's get started!

First, let us create the basic data structure that we will add to

class Stack<T> {}

Things to know about the code above:

  1. We define a new Swift class called Stack
  2. The Stack class is parameterized by some type T as denoted by <>

We will see shortly how the Type T is going to help us.

Now let us add the two basic operations of our Stack

class Stack<T> {    private var rep: [T]!    init() {        self.rep = []    }    public func push(element: T) {    }    public func pop() ->T? {    }
}

Above we add two methods: Push and Pop. The push method adds an element to the top of the stack, and pop removes an element from the top of the stack.

As you can see in the definitions for Push and Pop that both accept a parameter of type T, and return a value of Type T respectively. What does this mean? Remember how we defined the class Stack to be parameterized by Type T? The <T> used in the class definition tells the Swift compiler that we are defining a class that will use some Type T that will be defined at runtime. After defining the generic class we can use the generic type T anywhere within the class definition. This means that methods push and pop can also return and accept parameters of some type T that we can define at runtime.

Let us see what our implemented methods look like

class Stack<T> {    private var rep: [T]!    init() {        self.rep = []    }    public func push(element: T) {        self.rep.insert(element, at: 0)    }    public func pop() ->T? {        if self.rep.count > 0 {            return self.rep.remove(at: 0)        }    return nil    }}

As you can see our implementations for push and pop are completely agnostic to the underlying type that they are operating on.

Now let us see how we can use our newly created stack on multiple different types.

var stack = Stack<Int>()stack.push(element: 1)
stack.push(element: 2)
stack.push(element: 3)
stack.pop()stack.pop()stack.pop()// Output: 3, 2, 1

Here we are able to use our Stack to add and remove Ints, let us see if we can do the same with Strings

var stack = Stack<String>()stack.push(element: "1")
stack.push(element: "2")
stack.push(element: "3")
stack.pop()stack.pop()stack.pop()// Output: "3", "2", "1"

See how we were able to utilize the same stack for multiple different data types? That is the value of generics, code reuse.

Homework: Create a similar generic data structure that implements a Queue