Ketan Odedra
Ketan Odedra

Reputation: 1283

Update Dictionary Values with Key

this is my dictionary value

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

now i have to update cityid = "2", mobile = "456", name = "othername" and create same as above Dictionary with updated values. help me with this.

Upvotes: 0

Views: 1272

Answers (2)

Jayesh Thanki
Jayesh Thanki

Reputation: 2077

You can not update value in NSDictionary, so you have to use 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)

Upvotes: 1

Akhil
Akhil

Reputation: 170

Modify your code as below

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

you are forcefully unwraping the dictionary it is not recommended ..

Upvotes: 1

Related Questions