liveBook · Manning

SwiftPriorityQueue

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

SwiftPriorityQueue is an open-source Swift library providing a priority queue implementation.

SwiftPriorityQueue is an open-source Swift library for priority queues. It supports A* search by keeping frontier elements ordered so the item with the lowest f(n) is popped first. A binary-heap implementation provides logarithmic pushes and pops. section 2.2

Use the library by satisfying its ordering contract:

  • Define searchable elements such as Node as Comparable. section 2.2
  • Compare nodes using their f(n) value, calculated as cost plus heuristic. section 2.2
  • Create an ascending PriorityQueue and initialize it with the starting node. section 2.2
  • Pop frontier nodes while searching the maze, allowing A* to prioritize promising states. section 2.2

Using the queue for A*

An A* implementation initializes PriorityQueue<Node<StateType>> with ascending: true, stores the start node with its heuristic, and repeatedly pops the next node. A Manhattan-distance heuristic supplies the node ordering for a four-direction maze search. section 2.2

class Node<T>: Comparable, Hashable {
    let state: T
    let parent: Node?
    let cost: Float
    let heuristic: Float
    init(state: T, parent: Node?, cost: Float = 0.0, heuristic: Float = 0.0) {
        self.state = state
        self.parent = parent
        self.cost = cost
        self.heuristic = heuristic
    }

    var hashValue: Int { return Int(cost + heuristic) }
}

func < <T>(lhs: Node<T>, rhs: Node<T>) -> Bool {
    return (lhs.cost + lhs.heuristic) < (rhs.cost + rhs.heuristic)
}

func == <T>(lhs: Node<T>, rhs: Node<T>) -> Bool {
    return lhs === rhs
}

The Node definition shows the Comparable implementation that lets SwiftPriorityQueue order search states by cost plus heuristic. section 2.2

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Explains ordering, Comparable requirements, and heap complexity but defers implementing the priority queue itself.
Examples
Demonstrates A* maze solving with Comparable nodes, f(n) ordering, and Manhattan-distance heuristics.
What it assumes
Assumes familiarity with Swift Comparable and the cost, heuristic, and frontier concepts used by A* search.
What you can do after
Apply it via SwiftPriorityQueue to order A* frontier nodes by cost plus heuristic.
How it connects
Connects priority queues with A* search, binary heaps, Comparable, heuristics, and frontier management.

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.