Skip to content

Instantly share code, notes, and snippets.

@aydin-emre
Created February 13, 2022 13:49
Show Gist options
  • Save aydin-emre/d1810b1ff4d55ae6814aca1c754d48cd to your computer and use it in GitHub Desktop.
Save aydin-emre/d1810b1ff4d55ae6814aca1c754d48cd to your computer and use it in GitHub Desktop.
Queue Example on iOS, written in Swift..
import UIKit
public protocol Queue {
associatedtype Element
mutating func enqueue(_ element: Element)
mutating func dequeue() -> Element?
var isEmpty: Bool { get }
var peek: Element? { get }
}
public struct QueueArray<T>: Queue {
private var array: [T] = []
public init() {}
public var isEmpty: Bool {
array.isEmpty
}
public var peek: T? {
array.first
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
isEmpty ? nil : array.removeFirst()
}
}
extension QueueArray: CustomStringConvertible {
public var description: String {
String(describing: array)
}
}
var queue = QueueArray<String>()
queue.enqueue("A")
queue.enqueue("B")
queue.enqueue("C")
print(queue)
queue.dequeue()
print(queue)
print(queue.peek)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment