swiftQueues

Swift doesn't have a dedicated Queue struct. Let's create our own Queue struct.

As we did for the Stacks, we are going to create our Queue Struct.

A queue uses FIFO (first-in first-out) ordering and these are its basic operations:

  • add(element): Or enqueue(element), add an element.
  • remove(): Or dequeue(), remove and return an element.
  • peek(): Return the first element of the queue.
  • isEmpty()

First contact

Basically with an array we can do any type of operations, to create a Queue we only have to limit the behavior.

With the code below, you can see that with array methods, we can replicate a Queue functionality. append() to add(), removeFirst() to remove().

var queue: [String] = []

queue.append("A")
queue.append("B")
queue.append("C")
while !queue.isEmpty {
    let e = queue.removeFirst()
    print(e)
}

Output

A
B
C

Version 1: A generic struct

struct Queue<Element> {
    private var array: [Element] = []

    mutating func add(_ element: Element) {
        array.append(element)
    }

    mutating func remove() -> Element? {
        array.removeFirst()
    }

    func peek() -> Element? {
        array.first
    }

    var isEmpty: Bool {
        array.isEmpty
    }
}

Since the add() and remove() functions must modify the content or the array (which is an attribute of the Struct), then it is necessary that this function be mutating. Note that the peek() function does not modify or extract a value, it only reads the top element, that's why you don't need the mutating keyword.

Remember that if the function has only one line of code you can save the return keyword.

How to use

var queue = Queue<String>()

queue.add("A")
queue.add("B")
queue.add("C")

while !queue.isEmpty {
    let e = queue.remove()
    print(e ?? "")
}

Alternatively instead of using an array you can also use a LinkedList as the main container to create the Struct.

Updated for Swift 5.7