Swift: Getting the average

This entry is part 39 of 41 in the series Swift

Another method to get the average.

import UIKit

func calculateAverage(total: Int, countOfNumbers: Int) -> Int {
    return total / countOfNumbers
}

func average(algorithm: (Int, Int) -> Int, numbers: Int...) -> Int {
    var countOfNumbers = 0
    var total = 0
    
    for number in numbers {
        total += number
        countOfNumbers++
    }
    
    return algorithm(total, countOfNumbers)
}

let avg = average(calculateAverage, numbers: 3, 9, 6)

print(avg)

average

Swift: Getting the average

This entry is part 18 of 41 in the series Swift

Here we show how we could get the average of a few or more numbers. In this example, we are using a for loop and a swift function called reduce.

func averageLoop(numbers: Int...) -> Int {
    
    var sum = 0
    
    for number in numbers {
        sum += number
    }
    
    return sum / numbers.count
}

func averageReduce(numbers: Int...) -> Int {
    
    return numbers.reduce(0, combine: +) / numbers.count
    
}

var avgLoop = averageLoop(100, 200, 300)
var avgReduce = averageReduce(100, 200, 300,400,500,600)

swift