arrays - 用 Swift 修改数组中的对象?

标签 arrays swift for-loop nsdictionary

我有数组:

var arrDicContact = udContact.valueForKey("arrDicContact") as [NSDictionary]

我想更改数组中的一个联系人:

 for let dicx:NSDictionary in arrDicContact{
     if (dic.valueForKey("name") as String) == selectedName{
        //how to modify dic to newdic: dic = newdic
     }
 }

我可以使用 for 循环,其中 int i 从 0 到 arrDicContact.count-1。但它还没有退出...我喜欢 for loop (for...in...) 所以任何人都可以帮助我! :) 非常感谢。

最佳答案

假设我们有这样的数组:

var array:[NSDictionary] = [["name":"foo"],["name":"bar"],["name":"baz"]]

使用枚举

for (idx, dic) in enumerate(array) {
    if (dic["name"] as? String) == "bar" {
        array[idx] = ["name": "newBar"]
    }
}

迭代索引:

for idx in indices(array) {
    if (array[idx]["name"] as? String) == "bar" {
        array[idx] = ["name": "newBar"]
    }
}

更积极地,使用 map 替换整个 array:

array = array.map { dic in
    if (dic["name"] as? String) == "bar" {
        return ["name": "newBar"]
    }
    return dic
}

关于arrays - 用 Swift 修改数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28453785/

相关文章:

java - java中所有循环(for、while、do while)都可以相互表达吗?

javascript - 使用 jQuery 以数组或 csv 形式获取所有已检查输入的 rel 属性值

ios - swift -UITableView 'unable to dequeue a cell with identifier Cell'

javascript - 为什么不同函数中的嵌套循环 'I' 会发生变化?

swift - 未找到 UITableView 原型(prototype)单元格

ios - 如何对 Xcode 中输入到 TextField 中的整数值进行排序?

python - 使用列表理解对多个数组执行 cumsum

c++ vector 和数组使用相同的txt文件

java - 等式 Java 数组中的奇怪之处 : References vs. 指针

java - 如何从 ByteBuffer 中提取使用过的字节数组?