遍历 Swift 数组并更改值

Iterate through Swift array and change values

提问人:Mike Nathas 提问时间:3/4/2019 最后编辑:Mike Nathas 更新时间:3/4/2019 访问量:12358

问:

我需要更改 Swift 数组的值。 我的第一次尝试只是遍历,但这不起作用,因为我只得到每个元素的副本,并且更改不会影响原始数组。 目标是在每个数组元素中都有一个唯一的“索引”。

myArray = [["index": 0], ["index":0], ["index":0], ["index":0]]

counter = 0
for item in myArray {
  item["index"] = counter
  counter += 1
}

我的下一个尝试是使用 map,但我不知道如何设置递增值。我可以设置,但我需要一个递增的值。 使用map可以以何种方式实现?$0["index"] = 1

myArray.map( { $0["index"] = ...? } )

感谢您的帮助!

数组 swift xcode mapreduce

评论

0赞 ielyamani 3/4/2019
您能展示一下用于创建数组的代码吗?
0赞 Mike Nathas 3/4/2019
数组只是一个字典列表,这些字典不是在代码中创建的,而是从文件加载的,并且必须为每个字典添加一个不存在的键“index”的值
0赞 ielyamani 3/4/2019
请用任何其他信息编辑您的问题,使您的问题易于理解和在操场上重现
0赞 Mike Nathas 3/4/2019
在原始代码中添加了 myArray,以便可以复制它

答:

17赞 ielyamani 3/4/2019 #1

循环中的计数器是一个常数。要使其可变,您可以使用:for

for var item in myArray { ... }

但这在这里没有帮助,因为我们会变异,而不是 .itemmyArray

你可以用这种方式改变元素:myArray

var myArray = [["index": 0], ["index":0], ["index":0], ["index":0]]

var counter = 0

for i in myArray.indices {
    myArray[i]["index"] = counter
    counter += 1
}

print(myArray) //[["index": 0], ["index": 1], ["index": 2], ["index": 3]]

这里不需要变量:counter

for i in myArray.indices {
    myArray[i]["index"] = i
}

编写上述内容的功能方式是:

myArray.indices.forEach { myArray[$0]["index"] = $0 }

评论

0赞 Eduard Streltsov 8/27/2021
感谢您使用 forEach 而不是 map 的功能方式
0赞 Code Different 3/4/2019 #2

通过创建一个全新的数组来存储修改后的字典,如何采用更实用的方法:

let myArray = [["index": 0], ["index":0], ["index":0], ["index":0]]
let myNewArray = myArray.enumerated().map { index, _ in ["index": index] }
1赞 E.Coms 3/4/2019 #3

我找到了一个简单的方法,并想分享它。

关键是 的定义。如果以这种方式,它将成功:myArray

 let myArray : [NSMutableDictionary] = [["firstDict":1, "otherKey":1], ["secondDict":2, "otherKey":1], ["lastDict":2, "otherKey":1]]

 myArray.enumerated().forEach{$0.element["index"] = $0.offset}

 print(myArray)






 [{
firstDict = 1;
index = 0;
otherKey = 1;
 }, {
index = 1;
otherKey = 1;
secondDict = 2;
}, {
index = 2;
lastDict = 2;
otherKey = 1;
}]