今天看到一篇通过一个比较有意思的示例来讲解 reduce 函数使用的文章 reduce all the things,自己也依葫芦画瓢的在 Swift 4.0 下实现了一遍 :)
示例大致是这样的:
如下为美国各个城市的 persons 列表,其中每个 person 的结构包括姓名、所属城市(其中城市名字符串的逗号之后为州名,如 CA 为加利福尼亚州)、平均年龄。请使用 map/flatmap/filter/reduce 等函数来封装一个查询指定州的总人数和平均年龄,其中函数输入参数为州名,persons 列表。
/// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(_:_:)` method to produce a single value from the elements /// of an entire sequence. For example, you can use this method on an array /// of numbers to find their sum or product. /// /// The `nextPartialResult` closure is called sequentially with an /// accumulating value initialized to `initialResult` and each element of /// the sequence. This example shows how to find the sum of an array of /// numbers. /// /// ... ... /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// `initialResult` is passed to `nextPartialResult` the first time the /// closure is executed. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the sequence into a new accumulating value, to be used /// in the next call of the `nextPartialResult` closure or returned to /// the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. publicfuncreduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element)throws -> Result) rethrows -> Result
在注释中很清晰的描述了 reduce 的算法逻辑,给定一个初始化的 result,然后不断的通过调用 nextPartialResult 闭包来计算下一个 result,该闭包的参数为 (上一次执行后的 result 和 collection 中的元素),然后返回的 Result 再继续调用 nextPartialResult 闭包,直到返回最终的 result 值。