gpt4 book ai didi

arrays - (Index, value) Pairs while looping through a Array

转载 作者:行者123 更新时间:2023-11-28 15:37:58 25 4
gpt4 key购买 nike

在 Swift 2.0 中,以下代码有效:

import UIKit

var arr = [5, 77, 34, -22]

for (index, value) in enumerate(arr) {

// arr[index] = value + 1 This works, but the line below is more relevant for the following code.

arr[index] = arr[index] + 1

}

println(arr)

给予:

[6, 78, 35, -21]

我在 Swift 3.0 中使用以下代码进行了相同的尝试:

import UIKit

var arr = [5, 77, 34, -22]

var y = arr.count

for x in 0...y {

arr[x] = arr[x] + 1

}

print(arr)

但是,for 循环内的唯一一行出现错误,提示“错误:执行被中断,原因:EXC_BAD_INSTRUCTION”。关于哪里出了问题或我可以使用什么语法来获取第一个程序中的(索引,值)对,有什么想法吗?

最佳答案

只需删除 let,因为您没有声明任何新变量。

更好的是,只需使用 map:

let numbers = [5, 77, 34, -22]
let incremented = numbers.map{ $0 + 1 }

关于arrays - (Index, value) Pairs while looping through a Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44092814/

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