Last active
February 22, 2023 13:05
-
-
Save igorzhukov/4488bdb646c28b26a4fdc0b398edcf5f to your computer and use it in GitHub Desktop.
Stack 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
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