Stacks in Swift

Randall Leung
Dec 17, 2014 · 2 min read

A stack is an abstract data type or collection that helps organizes data in a particular order. This concept is based on the idea that information can be organized in a similar way on things work in the real world. The operations for adding an entity to the stack is known as push and the removal known as pop.


Think of a stack of dishes. The first dish placed on the table, while the next dish is placed on top of the first dish. Then the 3rd dish is placed on the 2nd dish, and so on and so forth. What you get is the newest dish is on top, while the first dish is always on the bottom of the stack. This process of adding dishes is push.

Now, when you wish to remove a dish, you remove it from the top of the stack(the last dish you placed on top). Not middle or the bottom of the dish stack. This process of removing a dish, is called pop. Pop is always removed from the top.

Thus, a stack is Last-In-First-Out (LIFO) data structure. Can you think real life examples that uses a stack?


We shall implement this data structure in Swift with Xcode’s Playgrounds.

First we create a Stack class. We then create an empty array that holds our stack called stackArray.

class Stack {
var stackArray = [String]()
//create push function
//create pop function

Since we know that a Stack has an operation called push, let’s create it. Remember push is putting the new dish on top of the previous dish.

func push(stringToPush: String){

Now lets create an operation for pop. Pop is taking the top dish out.

But we have to remember to do a check if the current stackArray is nil or not. If it is not nil, then we can remove the top dish. If it is nil, that means there are no dishes yet on the stack, thus returning nil. For good practice, lets return the string that we pop so the user knows what was removed.

func pop() -> String? {
if self.stackArray.last != nil {
var stringToReturn = self.stackArray.last
return stringToReturn!
} else {
return nil

Great. Lets test it. First, create an instance of our stack class.

var myStack = Stack()

myStack.push("First") //["First"]
myStack.push("Second") //["First","Second"]
myStack.push("Third) //["First","Second","Third"]
myStack.pop() //"Third"

And now you’ve implemented a simple Stack structure in Swift. In terms of efficiency, our stack provides O(1) for both storage and lookup.

    Randall Leung

    Written by