【问题标题】:Iterate through Swift array and change values遍历 Swift 数组并更改值
【发布时间】:2019-07-25 04:00:38
【问题描述】:

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

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

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

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

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

感谢您的帮助!

【问题讨论】:

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

标签: arrays swift xcode mapreduce


【解决方案1】:

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

for var item in myArray { ... }

但这在这里没有用,因为我们会改变 item 而不是 myArray 中的元素。

您可以这样改变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 }

【讨论】:

  • 感谢使用 forEach 而不是 map 的功能方式
【解决方案2】:

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

关键是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;
}]

【讨论】:

    【解决方案3】:

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

    let myArray = [["index": 0], ["index":0], ["index":0], ["index":0]]
    let myNewArray = myArray.enumerated().map { index, _ in ["index": index] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-13
      • 2012-11-08
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      相关资源
      最近更新 更多