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

Now that we have items on our stack, and we know how to peek at the one on the top, we need to implement the removal of the topmost item off the stack. We’ll call this method, pop().

As shown in the previous exercises, we need to operate on the LinkedList to return the head of the stack. We’ll leverage a removeHead() method in our code from the LinkedList class to achieve this.

Let’s get started!



In this step, we’ll build out the entire pop() method.

  1. Add a function to the Stack structure named pop() that returns an optional String. Note that similar to push() you should declare it as mutating since we are modifying the stack.

  2. Use the Swift guard statement that checks if calling the removeHead() method on list returns nil. Add a print statement saying Nothing left to remove! if it does. On the following line, return nil.

  3. Outside of the guard statement make sure to print the node’s data that was removed. And finally, return that data.


Now, let’s put all these methods into action together. After the Top dish: print statement, add four calls to pop(). Run your code. You should see your dishes moving off the stack in the reverse order they were placed on it. Because we add 3 but remove 4 we should see the Nothing left to remove! print statement as well.

Note that we are calling pop() but not using the result which will result in a compiler warning. You can add the code _ = before the calls to pop() to avoid this warning.

Give it a try!

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?