2015-02-11 151 views
3

我有數組:使用Swift修改數組中的對象?

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 
    } 
} 

我可以爲循環使用爲int i從0到arrDicContact.count-1。但它沒有退出......我喜歡循環(for ... in ...)所以有人幫助我! :)很多。

+0

在遍歷它 – DogCoffee 2015-06-03 02:43:53

回答

0

您需要改用NSMutableDictionary,因爲您無法編輯NSDictionary

然後你也有一個錯字。在你的if條款中,你使​​用dic,但你需要dicx

解決的是,您如果子句中後,你可以做這樣的事情:

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

假設我們有數組是這樣的:

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

使用enumerate

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

迭代結束indices

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 
} 
+0

我投給了這個答案你不應該修改數據收集/陣列/列表;只是一個Swift 2.0更新 - 使用枚舉如下:for(idx,dic)array.enumerate(){... – Yizhar 2016-01-28 16:22:36

+0

如果我們有結構數組應該如何? – 2016-05-26 18:50:49