Abstract Data Types (ADT)

This page is under construction. Please come back later.
#!/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()
Output
ADTStack.swift:39:6: warning: variable 'stack' was never mutated; consider changing to 'let' constant
37 |
38 | func main() -> Void {
39 | var stack:IntegerStack = IntegerStack()
| `- warning: variable 'stack' was never mutated; consider changing to 'let' constant
40 | for x:Int in 1...10 {
41 | stack.push(x)
10
10
9
8
7
6
5
4
3
2
1
Can't pop on empty stack!
#!/usr/bin/env swift;
/******************************************************************************
* Simple first program.
*
* Copyright © 2020 Richard Lesh. All rights reserved.
*****************************************************************************/
import Foundation
func main() -> Void {
print("Hello, world!")
exit(EXIT_SUCCESS)
}
main()
Output
Hello, world!
#!/usr/bin/env swift;
/******************************************************************************
* Simple first program.
*
* Copyright © 2020 Richard Lesh. All rights reserved.
*****************************************************************************/
import Foundation
func main() -> Void {
print("Hello, world!")
exit(EXIT_SUCCESS)
}
main()
Output
Hello, world!
Questions
Projects
More ★'s indicate higher difficulty level.
References
- [[Swift Community]]
- [[Swift Language Guide]]
- [[Swift Language Reference]]
- [[Swift Programming Language]], Apple Inc.
- [[Swift Doc]]
- [[We Heart Swift]]
- [[Swift Cookbook]]
- [[Swift Playground]]
- [[Swift at TutorialsPoint]]
- [[Hacking with Swift]]
Pure Programmer


