Swift Queues
One thing after another
3 min readMay 9, 2024
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.
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 var elements: [T] = []
func pop() -> T? {
guard !elements.isEmpty else { return nil }
return elements.removeLast()
}
func push(element: T) {
elements.append(element)
}
func peek() -> T? {
elements.last
}
func isEmpty() -> Bool {
elements.isEmpty
}
}