Swift Functional Programming: reduce

January 8th, 2018

Filed under: iOS Development, Mac Development | Be the first to comment!

The reduce function takes all the elements of a collection and combines them into a single value. Supply an initial value and a function or closure (unnamed function) to combine the elements.

The following code demonstrates how to calculate the average for a collection of test scores:

let testScores = [78, 96, 48, 65, 59, 91]

let average = testScores.reduce(0.0, { x, y in
    Double(x) + Double(y)
}) / Double(testScores.count)

The closure inside the call to reduce calculates the sum of the test scores. Divide the sum by the number of scores to calculate the average. I had to convert the scores and the array count to floating-point values to calculate the average accurately. Swift does not let you divide two integers and return a floating-point value. Dividing two integers yields an integer, which you can test in a playground with the following code:

let integerAverage = testScores.reduce(0, { x, y in
    x + y
}) / testScores.count

Dividing the two integers yields an average of 72 instead of 72.833333.

A Cleaner Way

My code example demonstrates the syntax for using reduce with closures, but the code could be cleaner. A cleaner way to calculate the average is to use reduce to calculate the sum and do the floating-point conversion when dividing.

let sum = testScores.reduce(0, +)
let average = Double(sum) / Double(testScores.count)

The code to call reduce is simpler in this version because there’s no closure to write.


Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *