我有3个字典的数组,看起来像这样:
array1 = [["measure1":"90", "measure2":"200","measure3":"23", "measure4":"190"],["measure1":"60", "measure2":"340","measure3":"531", "measure4":"2000"],["measure1":"210", "measure2":"2","measure3":"12", "measure4":"743"]]
然后我也有一个像这样的数组:
array2 = ["10","20","30"]
我试图按顺序将字典数组中所有“ measure4”的值替换为array2中的值(即第一个“ measure4”变为“ 10”,第二个“ 20”等)
感觉答案应该很简单,但是我一直在为in循环尝试各种不同的方法,并且没有什么可以带来正确的字典数组,看起来应该像这样:
array1 = [["measure1":"90", "measure2":"200","measure3":"23", "measure4":"10"],["measure1":"60", "measure2":"340","measure3":"531", "measure4":"20"],["measure1":"210", "measure2":"2","measure3":"12", "measure4":"30"]]
非常感谢您的帮助。
答案 0 :(得分:2)
for (i, x) in array2.enumerated() {
array1[i]["measure4"] = x
}
答案 1 :(得分:0)
尝试以下代码:
let new = array1.enumerated().reduce([[String: String]](), { acc, elemEnumerated in
var mutableDict = elemEnumerated.element
mutableDict["measure4"] = array2[elemEnumerated.offset]
return acc + [mutableDict]
})
答案 2 :(得分:0)
array1[0]["measure4"]? = array2[0]
array1[1]["measure4"]? = array2[1]
array1[2]["measure4"]? = array2[2]
或作为循环
for i in 0..<min(array1.count, array2.count) {
array1[i]["measure4"]? = array2[i]
}