#!/usr/bin/env swift; /****************************************************************************** * This program demonstrates the Stack ADT * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ import Foundation import Utils class IntegerStack { // Internal representation for the stack is a list private var stack:[Int] = [] public init() { stack = [] } public func pop() throws -> Int { if stack.count == 0 { throw RuntimeError("Can't pop on empty stack!") } return stack.removeLast() } public func push(_ value:Int) -> Void { stack.append(value) } public func peek() throws -> Int { if stack.count == 0 { throw RuntimeError("Can't peek on empty stack!") } return stack[stack.count - 1] } } func main() -> Void { var stack:IntegerStack = IntegerStack() for x:Int in 1...10 { stack.push(x) } do { print(String(try stack.peek())) for _:Int in 1...11 { print(String(try stack.pop())) } } catch let ex as RuntimeError { print(ex.localizedDescription) } catch { print("Unknown Exception!") } exit(EXIT_SUCCESS) } main()