Arrays 如何获取数组中部分整数(而不是全部整数)的和

Arrays 如何获取数组中部分整数(而不是全部整数)的和,arrays,swift,Arrays,Swift,我有一个数组,我希望能够得到数组中某些整数的和。它将始终是前2个、前3个或前4个元素,因此它不会获取第一个和最后一个整数,如果这样做更容易的话 我尝试了这段代码,但在它对数组中的所有整数求和之前,找不到阻止它的方法: let x = array.reduce(0, +) // array[lowerBound..<upperBound] ignore upperBound // array[lowerBound...upperBound] include upperBound // E

我有一个数组,我希望能够得到数组中某些整数的和。它将始终是前2个、前3个或前4个元素,因此它不会获取第一个和最后一个整数,如果这样做更容易的话

我尝试了这段代码,但在它对数组中的所有整数求和之前,找不到阻止它的方法:

let x = array.reduce(0, +)
// array[lowerBound..<upperBound] ignore upperBound
// array[lowerBound...upperBound] include upperBound

// Examples:

// Change 2 for the starting index you want to include
array[2..<array.count].reduce(0,+)

array[0..<array.count-2].reduce(0,+)

// Be careful with upper/lower bounds
尝试切片阵列:

let x = array.reduce(0, +)
// array[lowerBound..<upperBound] ignore upperBound
// array[lowerBound...upperBound] include upperBound

// Examples:

// Change 2 for the starting index you want to include
array[2..<array.count].reduce(0,+)

array[0..<array.count-2].reduce(0,+)

// Be careful with upper/lower bounds
//数组[lowerBound..尝试切片数组:

let x = array.reduce(0, +)
// array[lowerBound..<upperBound] ignore upperBound
// array[lowerBound...upperBound] include upperBound

// Examples:

// Change 2 for the starting index you want to include
array[2..<array.count].reduce(0,+)

array[0..<array.count-2].reduce(0,+)

// Be careful with upper/lower bounds

//数组[lowerBound..您可以使用
前缀
方法

let nums = [1, 2, 3, 4, 5]
let sum = nums.prefix(3).reduce(0, +)

print(sum) // 6
如果传递给前缀的值大于
nums.count
,则前缀将自动返回整个数组


您可以使用
前缀
方法

let nums = [1, 2, 3, 4, 5]
let sum = nums.prefix(3).reduce(0, +)

print(sum) // 6
如果传递给前缀的值大于
nums.count
,则前缀将自动返回整个数组


下面是一个函数,它将给定索引之间的
Int
s数组的元素相加(包括从0开始的索引):

let number=[1,2,3,4,5,6,7,8,9,10]
func sumUpRange(数字:[Int],from:Int,to:Int)->Int{

return numbers.enumerated().filter({index,num in index>=from&&index这里有一个函数,它将给定索引之间的
Int
s数组的元素相加(包括从0开始的索引):

let number=[1,2,3,4,5,6,7,8,9,10]
func sumUpRange(数字:[Int],from:Int,to:Int)->Int{
返回numbers.enumerated().filter({index,index中的num>=from&&index