gpt4 book ai didi

Swift - 将步幅与 Int 数组一起使用

转载 作者:行者123 更新时间:2023-11-28 07:34:13 25 4
gpt4 key购买 nike

我想将数字相加并每 4 个元素打印一次,但是我无法使用 stride 函数,如果我使用了错误的方法请解释更好的方法

var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13]

func addNumbersByStride(){
var output = Stride...
//first output = 1+2+3+4 = 10
//second output = 5+6+7+8 = 26 and so on
print(output)
}

最佳答案

看来你想使用 stride ...

let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13]

let by = 4
let i = stride(from: arr.startIndex, to: arr.endIndex, by: by)
var j = i.makeIterator()
while let n = j.next() {
let e = min(n.advanced(by: by), arr.endIndex)
let sum = arr[n..<e].reduce(0, +)
print("summ of arr[\(n)..<\(e)]", sum)
}

打印

summ of arr[0..<4] 10
summ of arr[4..<8] 26
summ of arr[8..<12] 42
summ of arr[12..<13] 13

关于Swift - 将步幅与 Int 数组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53708126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com