Swift Examples

Dave Braunschweig

Arrays

// This program demonstrates array processing, including:
// display, total, max, min, parallel arrays, sort,
// fixed arrays, dynamic arrays, and multidimensional arrays.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

import Foundation

func displayArray(array: [Int]) {
    for index in 0...array.count - 1 {
        print("array[" + String(index) + "] = " + String(array[index]))
    }
}

func demonstrateParallelArrays(names:[String], ages:[Int]) {
    for index in 0...names.count - 1 {
        print(names[index] + " is " + String(ages[index]))
    }
}

func demonstrateFixedArray() {
    var array: [Int] = [Int](repeating: 0, count: 5)

    srand(UInt32(time(nil)))
    for index in 0...4 {
        array[index] = random() % 100
    }
    print(array)
}

func demonstrateDynamicArray() {
    var array: [Int] = []

    srand(UInt32(time(nil)))
    for _ in 0...4 {
        array.append(random() % 100)
    }
    print(array)
}

func demonstrateMultidimensionalArray() {
    var game: [[String]]
    
    game = [
        ["X", "O", "X"],
        ["O", "X", "O"],
        ["X", "O", "X"]
    ]

    for row in 0...2 {
        for column in 0...2 {
            print(game[row][column], terminator:"")
            if column < 2 {
                print(" | ", terminator:"")
            }
        }
        print()
    }
}

func main() {
    var names: [String]
    var ages: [Int]
    var total: Int
    var maximum: Int
    var minimum: Int

    names = ["Lisa", "Michael", "Ashley", "Jacob", "Emily"]
    ages = [49, 48, 26, 19, 16]

    displayArray(array:ages)
    total = ages.reduce(0, +)
    maximum = ages.max()!
    minimum = ages.min()!

    print("total:", total)
    print("maximum:", maximum)
    print("minimum:", minimum)

    demonstrateParallelArrays(names:names, ages:ages)

    ages.sort()
    displayArray(array:ages)

    demonstrateFixedArray()
    demonstrateDynamicArray()
    demonstrateMultidimensionalArray()
}

main()

Output

array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49
Michael is 48
Ashley is 26
Jacob is 19
Emily is 16
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
[89, 41, 22, 56, 60]
[89, 41, 22, 56, 60]
X | O | X
O | X | O
X | O | X

References

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Programming Fundamentals Copyright © 2018 by Authors and Contributors is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book