Dershowitz123 Dershowitz123 - 1 year ago 57
Swift Question

Understanding reduce()

Suppose I've a code where I want to calculate the average of the numbers using the higher order function


var ofAvg = [1,2,3,4,5]

var doAvg = ofAvg.reduce(0) { $0 + $1 }

doAvg/ofAvg.count //This gives me the correct answer which in this case is 3.

But when I do:

var ofAvg = [1,2,3,4,5]

var doAvg = ofAvg.reduce(0) { ($0 + $1)/ofAvg.count }

I get the output as
. What wrong I'm I doing? Is my understanding of
not what it actually is? Is it possible to get the average without having to do
outside the


You need to do the division only once, after all summing is done:

var ofAvg = [1,2,3,4,5]

var doAvg = ofAvg.reduce(0) { $0 + $1 } / ofAvg.count

You don't even need seperate closure in this case, since + already has the same type that you're looking for ((Int, Int) -> Int), so you can just use it directly:

var doAvg = ofAvg.reduce(0, combine: +) / ofAvg.count

P.S. Please use better names. Variables should be nouns (or noun phrases), and functions should be verbs (or verb phrases).