iOS开发SwiftiOS开发

reduce用法详解

2015-12-11  本文已影响237人  Hollylord

基础知识

Reduce 的基础思想是将一个序列转换为一个不同类型的数据,期间通过一个累加器(Accumulator)来持续记录递增状态。

func reduce<T>(initial: T, combine: (T, Self.Generator.Element) -> T) -> T
func combinator(accumulator: Int, current: Int) -> Int { 
    return accumulator + current
}

[1, 2, 3].reduce(0, combine: combinator)
// 执行步骤如下
combinator(0, 1) { return 0 + 1 } = 1
combinator(1, 2) { return 1 + 2 } = 3
combinator(3, 3) { return 3 + 3 } = 6
= 6

初始值0会跟数组第一个元素运算,成为累加值,然后这个值在与数组第二个元素运算成为第二个累加值,以此类推,返回最后的结果。

实际用法

func rmap(elements: [Int], transform: (Int) -> Int) -> [Int] { 
    return elements.reduce([Int](), combine: { (var acc: [Int], obj: Int) -> [Int] in 
      acc.append(transform(obj)) 
      return acc })
    }

print(rmap([1, 2, 3, 4], transform: { $0 * 2}))
// [2, 4, 6, 8]

combine这个闭包有2个参数,$1表示每次运算的累加值,这个值也是最后要返回的,所以返回的类型也必须跟它保持一致;$2是便利数组后当前参与运算的一个数组元素。

分解上式代码:
上一篇下一篇

猜你喜欢

热点阅读