Data Structure in Swift (Stack) — Part 3

Previously, we learned how to work with Linked List in Swift language. Today, we are going to implement Stack using Swift.

Nitin Aggarwal
3 min readFeb 12, 2020

A stack is a data structure that allows us to arrange the items in a linear way. A stack basically follows the LIFO (Last In First Out) mechanism to insert or deletion of items. It means the last item added in Stack will be removed first.

In Stack, we can perform some operations like:

  • push(): To insert an element.
  • pop(): To remove the top-most element.
  • peek(): To only get the top-most element.

A stack is used almost in all the programming languages. In iOS, some of the things are based on Stack like:

  • UINavigationController uses the Stack to push and pop the controllers.
  • Memory allocations for local variables are managed by Stack.

Now, move to the coding part in that we will learn how to implement Stack using Swift language.

Here, we will learn the Stack implementation using Array and without Array.

Stack with Array:

Example:

Stack example with String type
Stack example with Int type

In the above code, we learned how to implement Stack with Array with the Generics. But we can use the Linked List concept to implement a Stack.

Stack without Array

Here, we will use the concept of Linked List.

Node class
Stack class
Stack example of String type
Stack example with custom class type

In the Stack, both the operation push and pop are performed with time complexity O(1).

How we can see the use of Stack in the real world?

  • In iOS, a UINavigationController uses the Stack for push and pop
  • Undo/Redo functionality
  • Go back and forward in Web Browsers
  • Many more

I hope you enjoyed this article, so don’t forget to Clap it and follow me.

Get the full source code here: GitHub

Other Stuff

  • See the previous stories of this series ‘Data Structure’:

Linked List

Array & Dictionary

  • See the other stories on iOS (Swift):

Network Framework in iOS (Swift)

Any Vs AnyObject in Swift

Extended UIColor in Swift

Spacing between each character in UILabel

Happy Coding !!

Nitin A

--

--

Nitin Aggarwal
Nitin Aggarwal

Written by Nitin Aggarwal

Lead iOS Engineer, Mentor, Author, Writer; 📙 Released "iOS Interview Handbook" 🔗 topmate.io/nitinagam17/827990

Responses (3)

Write a response