
上QQ阅读APP看书,第一时间看更新
The reduce function
The reduce function is a higher-order function that reduces an array to a single value. It takes two parameters: a starting value and a function, which takes a running total and an element of the arrays as parameters and returns a new running total. Consider the following example:
let total = numbers.reduce(0) { $0 + $1 }
The map, filter, and reduce functions accept a closure as the last parameter, so we were able to use the trailing closure syntax. These higher-order functions will be covered in detail in Chapter 6, Map, Filter, and Reduce.