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

Series Navigation<< Swift: Declaring an array with the same value
Swift Programming Tutorial For Beginners 2015 >>