Created
February 13, 2022 13:49
-
-
Save aydin-emre/d1810b1ff4d55ae6814aca1c754d48cd to your computer and use it in GitHub Desktop.
Queue Example on iOS, written in 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 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