zip、reduce 和 combine in Swift 的说明

Explanation of zip, reduce and combine in Swift

有人可以为我分解这个代码示例吗? zipreduce 有一定道理,但是 combine: 的情况让我感到困惑。任何帮助将不胜感激。

let a = [5, 6, 7]
let b = [3, 6, 10]

let pointsAlice = zip(a, b).reduce(0, combine: { [=11=] + (.0 > .1 ? 1 : 0) } )
let pointsBob = zip(b, a).reduce(0, combine: { [=11=] + (.0 > .1 ? 1 : 0) } )

print("\(pointsAlice) \(pointsBob)") // 1 1

zip(a, b) 生成一个元组序列,将 ab

的值配对
[(5, 3), (6, 6), (7, 10)]

该序列一次传递给 reduce 一个元组。 reduce 有两个参数。第一个是 runningTotal 的初始值,第二个是名为 combine 的闭包,它对序列中的每一项进行一次调用一次的操作。

在这种情况下,代码正在计算 Alice 和 Bob 得分较高的分数。

默认值 [=19=].0.1 的使用使代码有点难以解释,但这是等效版本:

let pointsAlice = zip(a, b).reduce(0, combine: { (runningTotal, scores) in
    return runningTotal + (scores.0 > scores.1 ? 1 : 0) } )

对于序列中的每个值(例如 (5, 3)),该值作为 scores 传递给 combine 闭包,并且 runningTotal 获取该值来自 reduce 的前一次迭代。 scores.0 指代元组中的第一个值,scores.1 指代元组中的第二个值。最初的 runningTotal 是传递给 reduce0

如果第一个分数更高,combine 闭包返回 runningTotal1,否则返回加 0。然后将该值作为新的 runningTotal 值与下一个 scores 元组一起传递到 combine 的下一次调用中。

最终结果是第一个分数较高的分数的计数。