使用键更新字典值

时间:2018-02-08 10:30:07

标签: ios nsdictionary nsuserdefaults swift4

这是我的字典值

var dict: NSDictionary = NSDictionary()
dict = pref.object(forKey: KEY_USER_LOGIN_INFO) as! NSDictionary
print(dict as Any)

{
    cityId = 1;
    cityName = Dammam;
    countryId = 1;
    mobile = 123;
    name = "My name";
}

现在我必须更新cityid =" 2",mobile =" 456",name =" othername"  并使用更新的值创建与上面相同的词典。  帮助我。

2 个答案:

答案 0 :(得分:1)

修改您的代码,如下所示

 var dict = pref.object(forKey: KEY_USER_LOGIN_INFO) as! Dictionary<String,Any>
dict["cityid"] = "2"
dict["mobile"] = "456"
dic["name"] =  "other name"

你强行打开字典不推荐..

答案 1 :(得分:1)

您无法更新NSDictionary中的值,因此您必须使用NSMutableDictionary

var dict: NSMutableDictionary = NSMutableDictionary()
dict = (pref.object(forKey: KEY_USER_LOGIN_INFO) as! NSDictionary).mutableCopy() as! NSMutableDictionary
dict["cityId"] = 2
dict["mobile"] = 456
dict["name"] = "othername"
print(dict)