Skip to content

Instantly share code, notes, and snippets.

@igorzhukov
Last active February 22, 2023 13:05
Show Gist options
  • Save igorzhukov/4488bdb646c28b26a4fdc0b398edcf5f to your computer and use it in GitHub Desktop.
Save igorzhukov/4488bdb646c28b26a4fdc0b398edcf5f to your computer and use it in GitHub Desktop.
Stack in #swift
public struct Stack<Element> {
private var storage: [Element] = []
public init() { }
public init(_ elements: [Element]) {
storage = elements
}
public mutating func push(_ element: Element) {
storage.append(element)
}
@discardableResult
public mutating func pop() -> Element? {
storage.popLast()
}
public func peek() -> Element? {
storage.last
}
public var isEmpty: Bool {
peek() == nil
}
public var count: Int {
storage.count
}
}
extension Stack: CustomDebugStringConvertible {
public var debugDescription: String {
"""
\(storage.map { "\($0)" }.reversed().joined(separator: "\n"))
-----------
"""
}
}
extension Stack: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
storage = elements
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment