2016-05-29 20 views
0

“+”的函数如何返回一个看起来像它的数组,添加每个索引的所有前面的数字?我得到了0 + 1 = 1,1 + 2 = 3,1 + 2 + 3 + 4 = 10,但是我很难将组合功能与“+”联系起来,因为它只是一个“+”这个数组扩展在做什么“+”闭包?

extension Array { 
func accumulate<U>(initial: U, combine: (U, Element) -> U) -> [U] { 
    var running = initial 
    return self.map { next in 
     running = combine(running, next) 
     return running 
     } 
    } 
} 

let test = [1,2,3,4] 
test.accumulate(0, combine: +) 
// returns [1, 3, 6, 10] 
+0

这只是内置'reduce'如何工作的演示。在我的在线书籍的这一部分中进行了解释:http://www.apeth.com/swiftBook/ch04.html#_array_enumeration_and_transformation – matt

+0

查看Swift参考中的“Operator Functions”部分。 –

+0

@MartinR:谢谢,这是我需要连接点的缺失部分 –

回答

1

combine是一个函数。说combine(running, next)调用函数,它需要两个参数。在Swift中,+(与其他所有运算符一样)的一个函数。因此,当combine+时,调用combinerunning添加到next并返回结果。