How do I implement a priority queue in Swift?

Implementing a priority queue in Swift allows you to efficiently manage a collection of elements based on their priority. Below is an example of how you can create a simple priority queue class using a min-heap data structure.

class PriorityQueue { private var elements: [(priority: Int, value: T)] = [] func push(_ value: T, priority: Int) { elements.append((priority, value)) elements.sort(by: { $0.priority < $1.priority }) } func pop() -> T? { return elements.isEmpty ? nil : elements.removeFirst().value } func peek() -> T? { return elements.first?.value } var isEmpty: Bool { return elements.isEmpty } var count: Int { return elements.count } } // Example usage let priorityQueue = PriorityQueue() priorityQueue.push("Low priority task", priority: 5) priorityQueue.push("High priority task", priority: 1) priorityQueue.push("Medium priority task", priority: 3) while !priorityQueue.isEmpty { print(priorityQueue.pop()!) // Output: High priority task, Medium priority task, Low priority task }

priority queue Swift priority queue Swift data structures min-heap priority queue implementation