Implementing Stack and Queue using Swift

Rajesh Budhiraja
2 min readAug 8, 2024

Implementing Stack or Queue using Swift is very straightforward. This code is often needed in different areas hence to avoid reinventing the wheel I wanted to put it down somewhere. I hope it helps you as well.

Stack

If you’re not already familiar with stacks, they are a type of data structure that operates on a Last-In-First-Out (LIFO) principle. This means that elements are added to and removed from only one end of the structure. In other words, the most recently added item is the first one to be removed. You can think of it like a stack of plates: you add new plates on top and take the top plate off first.

The operations supported on Stack are:

  1. Push
  2. Pop
  3. Peek
  4. Is Empty
  5. Count
final class Queue<Element> {

// Internal array to hold queue elements
private var items: [Element] = []

// Adds an item to the end of the queue
func enqueue(_ item: Element) {
items.append(item)
}

// Removes and returns the item from the front of the queue
func dequeue() -> Element? {
guard !items.isEmpty else {
return nil
}
return items.removeFirst()
}

// Returns the item at the front of the queue without removing it
func peek() -> Element? {
return items.first
}

// Returns true if the queue is empty, false otherwise
var isEmpty: Bool {…

--

--