用Swift修改数组中的对象? [英] Modify Object in Array with Swift?

查看:735
本文介绍了用Swift修改数组中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数组:

pre $ var $ argDicContact = udContact.valueForKey(arrDicContact)as [NSDictionary]

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

<$ p
if(dic.valueForKey(name)as String)== selectedName {
//如何将dic修改为newdic :dic = newdic
}
}

我从0到arrDicContact.count-1。但它是如此没有退出...我喜欢循环(for ...在...)所以有人帮助我! :)

解决方案

假设我们有这样的数组:

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

使用枚举

$ bic b






ar{
array [idx] = [name:newBar]
}
}


$ b $ p indices 的迭代:

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

更积极地,将整个<$ c $ map

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


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.

解决方案

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
}

这篇关于用Swift修改数组中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆