Skip to main content

Command Palette

Search for a command to run...

Algorithms In Swift: Stacks

How to create a stack using Swift

Updated
2 min read
Algorithms In Swift: Stacks

What's a Stack?

A stack is a simple way to temporarily store and manage data that works similarly to an array. It’s a collection of items where you can only view the current item (peek) add an item (push), or remove (pop) an item from the top.

  • peek: View the current item.

  • push: Adding an item.

  • pop: Removing an item.

Stacks follow a Last In, First Out (LIFO) principle, meaning the last item you added is the first one to be removed. Here's a nice visualization provided by BYJU:


Image of stack from BYJU


Why is it useful?

A stack is useful in programming because it helps keep track of tasks and their order in a simple and organized way. It allows you to handle complex operations by dealing with the most recent items first. This makes it easier to manage things like undoing actions or handling temporary data in a clear and orderly manner.

How can we build it?

Let's take a look at how we can build a stack in eight steps using Swift:

// 1. Create a Stack as a generic struct that can hold any type <T>.
public struct Stack<T> {
    // 2. Create an array to hold the values of the Stack
    private var array: [T] = []
    // 3. Create a function to initialize a new stack.
    public init() { }
    // 4. Create a function to push elements onto the end of the array. 
    public mutating func push(_ element: T) { array.append(element) }
    // 5. Create a function to pop elements off the end of the array.
    public mutating func pop() -> T?        { return array.popLast() }
    // 6. Create a function to view the last element of the array.
    public func peek() -> T?                { return array.last }
    // 7. Create a variable to check if the array is empty or not.
    public var isEmpty: Bool                { return array.isEmpty }
    // 8. Create a variable to check how many elements are in the array.
    public var count: Int                   { return array.count }
}

Next, we can play around with and test the stack:

var stackOfBooks = Stack()
stackOfBooks.push("Book 1")
stackOfBooks.push("Book 2")
stackOfBooks.push("Book 3")
print(stackOfBooks)
stackOfBooks.peek()
print(stackOfBooks)
stackOfBooks.pop()
print(stackOfBooks)

Conclusion

Stacks are commonly used throughout programming. This is just one example of how to create a basic one for a simple scenario. For a more complex use case, you can check out how Apple uses the concept of a stack in SwiftUI as a NavigationStack to manage what a user sees on screen.

Programming

Part 12 of 17

Articles and tutorials about programming and computer science concepts.

Up next

Create A System-Wide .gitignore File

Save Yourself From Copy-Paste Groundhog's Day

More from this blog

Damian Robinson | Online

20 posts

The blog and business site of Damian Robinson. You will find tutorials about programming and cybersecurity, and articles pertaining to various interests or pursuits of the author.