Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Stack Data Structure
import Foundation
public struct Stack<Element>
{
private var storage: [Element]
public init()
{
self.storage = [Element]()
}
public mutating func push(_ element: Element) -> Void
{
self.storage.insert(element, at: 0)
}
public mutating func pop() -> Element?
{
return self.storage.removeFirst()
}
public func whosOnTop() -> Element?
{
return self.storage.first
}
}
//
// TEST
//
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
if let top = stack.whosOnTop()
{
print("Top \(top)")
}
print(stack)
if let fuera = stack.pop()
{
print("Fuera: \(fuera)")
}
print(stack)
stack.push(5)
print(stack)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.