Skip to main content
Engineering LibreTexts

6.16: Swift Examples

  • Page ID
    10686
  • Arrays

    // This program demonstrates array processing, including:
    // display, total, max, min, parallel arrays, sort
    // multidimensional arrays, and dynamic 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 displayParallel(names:[String], ages:[Int]) {
        for index in 0...names.count - 1 {
            print(names[index] + " is " + String(ages[index]))
        }
    }
    
    func displayMultidimensional() {
        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 dynamicArray() {
        var array: [Int] = []
    
        srand(UInt32(time(nil)))
        for _ in 0...4 {
            array.append(random() % 100)
        }
        print(array)
    }
    
    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)
    
        displayParallel(names:names, ages:ages)
    
        ages.sort()
        displayArray(array:ages)
    
        displayMultidimensional()
        dynamicArray()
    }
    
    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
    X | O | X
    O | X | O
    X | O | X
    [93, 3, 7, 35, 59]