reduce
Swift中数组的reduce方法用于做序列元素的累加,如数组元素的累加, 函数原型:
@inlinable public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result参数:
- initialResult: 初始值, The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed.
- nextPartialResult: 下一次累加的基准值
示例:
var arr = [1, 2, 3, 4, 5, 6, 7, 8]/// initialResult: Result 初始值;/// nextPartialResult:(Result, Int) 下一轮盘算值, Result = initialResult + Int/// Result是每轮盘算的返回值(效果), Int 是数组元素/// -> Result 返回值/// `arr.reduce(initialResult: Result, nextPartialResult: (Result, Int) throws -> Result(Result, Int) throws -> Result>)`var sum = arr.reduce(100) { partialResult, value in print("\(value) --> \(partialResult)") return partialResult + value // return 可省略}// 初始值是100,第一步就是:// 100 + 1// 再把2加上 --> 100 + 1 + 2// 再把3加上 --> 100 + 1 + 2 + 3// ...print(sum) // 136固然,也有好吃的语法糖,效果是一样的: |