Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

reduce

The reduce function is applied to a collection of a given type, taking two parameters--an initial value of any type, and a closure. This closure takes two parameters--the first is of the initial type and the second is the same type as the collection. Then reduce applies the closure to the initial value and the first element of the collection. The result of that application is used as the first argument to another call of that closure, the second element being the next element of the collection, and so on. When all elements in the array have been processed, the accumulated result is returned:

let totalUnits = units.reduce(0, {$0 + $1}) 

This code returns the sum of the elements in the totalUnits array.

As was the case with map, the returned value does not need to be the same type as the type of the collection elements:

let unitsString = units.reduce("", {"\($0)\($1)"}) 

This code produces a String object, "0123456789".

The initial value passed to reduce is not necessarily 0, or an empty value:

let totalUnits = units.reduce(1, {$0 * $1})