使用键更新字典值

Update Dictionary Values with Key

这是我的字典值

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" 并使用更新的值创建与上面相同的字典。 帮我解决这个问题。

修改你的代码如下

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

你被强制解包了不推荐的字典..

您无法更新 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)