首页 > 解决方案 > 从特定元素添加数组中的快速求和数

问题描述

假设我在下面的数组中有一些数字

let numberArray = [1, 3, 4, 6, 9, 14, 16]

我知道如何通过使用 reduce 方法来总结它们,但是如何开始从特定元素添加数字。例如:

//Sum all up by reduce
let sumAll = numberArray.reduce(0, +)
//sumAll = 53 

//I want to start counting from the fourth element in the array which is 6
//so the total should be 45. [6 + 9 + 14 + 16]

我应该使用什么方法来实现这一点?
提前致谢。

标签: arraysswiftsum

解决方案


您可以使用dropFirst(_:)或使用范围作为索引。

如果它不是一个固定的数字,你可以先用它firstIndex(of:)来确定你想要开始的索引。

numberArray.dropFirst(3).reduce(0, +)
numberArray[3...].reduce(0, +)

推荐阅读