Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify Object in Array with Swift?

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.

like image 601
Binladenit Tran Avatar asked Nov 30 '22 18:11

Binladenit Tran


1 Answers

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
}
like image 103
rintaro Avatar answered Jan 06 '23 08:01

rintaro