Last active
February 24, 2020 16:36
-
-
Save schmittsfn/cfa350a7aa228aea676e3cabb5f91e1a to your computer and use it in GitHub Desktop.
A list of Queue data types for swift
This file contains hidden or 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
| import Foundation | |
| protocol Queuable { | |
| associatedtype T | |
| var items: [T] { get set } | |
| } | |
| extension Queuable { | |
| mutating func enqueue(element: T) { | |
| items.append(element) | |
| } | |
| mutating func dequeue() -> T? { | |
| if items.isEmpty { | |
| return nil | |
| } | |
| else { | |
| return items.removeFirst() | |
| } | |
| } | |
| } | |
| struct Queue<T>: Queuable { | |
| var items: [T] = [] | |
| } | |
| struct ExecutionQueue<T>: Queuable { | |
| var items: [T] = [] | |
| mutating func executeAll(with closure: (T) -> Void) { | |
| for _ in 0..<items.count { | |
| guard let item = dequeue() else { | |
| assertionFailure("dequeing from empty queue") | |
| return | |
| } | |
| closure(item) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment