Skip to content

Instantly share code, notes, and snippets.

@aydin-emre
Created February 10, 2022 06:57
Show Gist options
  • Save aydin-emre/edc8be4af0eceee6b4fa705f11a64d71 to your computer and use it in GitHub Desktop.
Save aydin-emre/edc8be4af0eceee6b4fa705f11a64d71 to your computer and use it in GitHub Desktop.
Stack Example on iOS, written in Swift..
import UIKit
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: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
storage = elements
}
}
extension Stack: CustomStringConvertible {
public var description: String {
"""
\n------- Top (Last pushed) -------
\(storage.map { "\($0)" }.reversed().joined(separator: "\n"))
----- Bottom (First pushed) -----\n
"""
}
}
// Example: Int
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
print(stack)
if let poppedElement = stack.pop() {
print("Popped: \(poppedElement)")
}
// Example: String
let array = ["A", "B", "C", "D"]
var stackString = Stack(array)
stackString.pop()
print(stackString)
// Example: Double
var stackDouble: Stack = [1.0, 2.0, 3.0, 4.0]
stackDouble.pop()
print(stackDouble)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment