Modify Object in Array with Swift?

戏子无情 提交于 2019-11-29 22:32:06

问题


I have array:

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

and i want to change one contact in array:

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

i can use for loop with int i from 0 to arrDicContact.count-1. But it's so not exited... i like for loop (for...in...) So anybody help me! :) Tks a lot.


回答1:


Assuming we have the array like this:

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

Using enumerate

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

Iterate over indices:

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

More aggressively, replace whole array using map:

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



回答2:


You need to use an NSMutableDictionary instead, because you can't edit a NSDictionary.

Then you've got also a typo. In your if-clause you use dic but you need dicx.

After resolving that, in your if-clause you can do something like that:

if (dicx.valueForKey("name") as String) == selectedName{
  dicx.setValue(value: yourObject, forKey: yourKey)
}


来源:https://stackoverflow.com/questions/28453785/modify-object-in-array-with-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!