Skip to content

Instantly share code, notes, and snippets.

@ntnmrndn
Created July 27, 2018 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntnmrndn/72fca7d697e864799ec815ec1351b7d2 to your computer and use it in GitHub Desktop.
Save ntnmrndn/72fca7d697e864799ec815ec1351b7d2 to your computer and use it in GitHub Desktop.
Swift LIFO Queue
/// Last in First Out Operation queue.
class LIFOOperationQueue {
enum Priority {
case high
case low
}
private let queue: DispatchQueue
private var highPriorityOperations = [Operation]()
private var lowPriorityOperations = [Operation]()
init(queue: DispatchQueue) {
self.queue = queue
}
private func next() {
if let operation = highPriorityOperations.first {
highPriorityOperations.remove(at: 0)
queue.async {
operation.start()
}
} else if let operation = lowPriorityOperations.first {
lowPriorityOperations.remove(at: 0)
queue.async {
operation.start()
}
}
}
/// Add an operation to the queue. Adding a duplicate operation cause it to be bumped to the top of the queue.
func addOperation(operation: Operation, priority: Priority) {
queue.async {
switch priority {
case .high:
if let index = self.highPriorityOperations.index(of: operation) {
self.highPriorityOperations.remove(at: index)
}
self.highPriorityOperations.insert(operation, at: 0)
case .low:
if let index = self.lowPriorityOperations.index(of: operation) {
self.lowPriorityOperations.remove(at: index)
}
self.lowPriorityOperations.insert(operation, at: 0)
}
self.queue.async {
self.next()
}
}
}
///XXX Remove?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment