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

Series Navigation<< Swift: Inheritance
Swift: Test if an array is empty >>

Leave a comment

Leave a Reply