Skip to content

Instantly share code, notes, and snippets.

@9bany
Created April 18, 2021 12:18
Show Gist options
  • Save 9bany/a91ad73515a3e9b7b881a32698e0f048 to your computer and use it in GitHub Desktop.
Save 9bany/a91ad73515a3e9b7b881a32698e0f048 to your computer and use it in GitHub Desktop.
Stack structure in Swift
struct Stack<T>: CustomStringConvertible {
var description: String {
let title = "==== Stack ==== \n"
let body = self.array.map{ "\($0)" }.reversed().joined(separator: "\n")
let end = "\n==============="
return title + body + end
}
private var array: [T] = []
mutating func push(_ item: T) {
self.array.append(item)
}
mutating func pop() -> T? {
return self.array.popLast()
}
func peek() -> T? {
return self.array.last
}
}
@9bany
Copy link
Author

9bany commented Apr 18, 2021

Example

var stringStack = Stack<String>()

stringStack.push("hello man")

stringStack.push("fuck")

print(stringStack)

stringStack.pop()

stringStack.peek()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment