Log in from a computer to take this course

You'll need to log in from a computer to start Introduction to Algorithms and Linear Data Structures in Swift. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

As you may recall, a stack is a linear data structure that contains an ordered set of data that follows a LIFO (last in, first out) protocol for accessing its data. A stack can be imagined as a literal stack of dishes to wash. As people finish eating they put their plate on top of the stack. The dishwasher will then take the plate off starting at the top of the stack. Since you have an understanding of how stacks work in theory, now let’s see how they can be useful in the wild – with Swift!

Remember that there are three main methods we want our stacks to have:

  • .push(): adds data to the top of the stack
  • .pop(): removes data from the top of the stack
  • .peek(): views the data at the top of the stack without removing it

We will also need to consider the stack’s size and tweak our methods a bit so that our stack does not “overflow” or “underflow”.

If you’ve taken our course where we created a linked list, you’ll see that many of the methods we created there will work perfectly for our stack implementation. To create a stack, we will use both our well-established LinkedList and Node data structures.

Let’s get started building our Stack struct!

Instructions

1.

Take a look at the right in Stack.swift to see the provided, empty Stack struct.

The first thing we need in our creation of a Stack data structure is a private property called list which will hold a new LinkedList instance.

Add the private property and initialize it to a new LinkedList().

2.

Our next step is to create some logic to determine if the Stack is empty or not. Let’s use Swift’s computed property language feature to create a property called isEmpty of Bool type. As you recall a computed property has the form:

var propertyName: type { return value }

We will want to return true if the list.head is equal to nil and false otherwise.

3.

Now that we have created our essential Stack struct, lets create a stack instance and assign it to a variable called dishes. Once you create it print out the value of the computed property isEmpty().

Add this code after your Stack structure definition.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?