Swift Queues

One thing after another

Steven Curtis
3 min readNov 1, 2024
Photo by Heather Suggitt on Unsplash

I’ve previously written an article about stacks and I think that is a good starting place for today’s article on the queue data structure as implemented in Swift.

But I can do better. So onto this article, where I’m going to explore a basic queue implementation, identify performance bottlenecks and write a *better* implementation.

Whether you’re new to Swift or looking to refine your data structure skills, this article will help you gain a deeper understanding of queues and their significance in building performant iOS applications.

Here is a simple representation of the stack:

class Stack<T> {
var elements = [T]()
func pop () -> T? {
if let last = elements.last {
elements = elements.dropLast()
return last
}
return nil
}

func push(_ element: T) {
elements.append(element)
}
}

If I were to rewrite this data structure today I might update it to make the class final and to use removeLast to simplify the logic but generally I’m comfortable with this LIFO (Last in, First Out Data structure) as long as I (finally) make that array private. I still prefer reference semantics for this type of data structure so I came up with:

final class Stack<T> {
private…

--

--