Created
February 10, 2022 06:57
-
-
Save aydin-emre/edc8be4af0eceee6b4fa705f11a64d71 to your computer and use it in GitHub Desktop.
Stack 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 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