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]
这只是内置'reduce'如何工作的演示。在我的在线书籍的这一部分中进行了解释:http://www.apeth.com/swiftBook/ch04.html#_array_enumeration_and_transformation – matt
查看Swift参考中的“Operator Functions”部分。 –
@MartinR:谢谢,这是我需要连接点的缺失部分 –