Skip to content

Instantly share code, notes, and snippets.

@nitin-agam
Created February 12, 2020 18:17
Show Gist options
  • Save nitin-agam/e3d41be735729a0e7359a050e45d061c to your computer and use it in GitHub Desktop.
Save nitin-agam/e3d41be735729a0e7359a050e45d061c to your computer and use it in GitHub Desktop.
struct Stack<T>: CustomStringConvertible {
// array of items
var items: [T] = []
// to print the formatted description
var description: String {
return "---- Stack begin ----\n" +
items.map({ "\($0)" }).joined(separator: "\n") +
"\n---- Stack End ----"
}
// push
mutating func push(_ item: T) {
self.items.insert(item, at: 0)
}
// pop
@discardableResult
mutating func pop() -> T? {
return self.items.removeFirst()
}
// peek item
@discardableResult
func peek() -> T? {
guard let firstItem = self.items.first else { return nil }
return firstItem
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment