Created
July 27, 2018 04:07
-
-
Save ntnmrndn/72fca7d697e864799ec815ec1351b7d2 to your computer and use it in GitHub Desktop.
Swift LIFO Queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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