Search code examples
iosnsdictionarynsuserdefaultsswift4

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.


Solution

  • 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 ..