Skip to content

Instantly share code, notes, and snippets.

@derekcoder
Last active April 9, 2020 07:32
Show Gist options
  • Save derekcoder/efad42c58156f3c0a49241c5c01f2105 to your computer and use it in GitHub Desktop.
Save derekcoder/efad42c58156f3c0a49241c5c01f2105 to your computer and use it in GitHub Desktop.
The implementation of Stack data structure in Swift
//
// Stack.swift
//
// Created by Derek on 18/12/19.
// Copyright © 2019 DerekCoder. All rights reserved.
//
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
}
}
extension Stack: CustomStringConvertible {
public var description: String {
"""
---- top ----
\(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