I have simple Dictionary which is defined like :
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
But later I want to add some element into this dictionary which is 3 : "efg"
But I have no idea that how can I perform this action I searched a lot on internet but nothing helps me.
Can anybody tell me how can I append 3 : "efg"
into this existing dictionary?
If your dictionary is
Int
toString
you can do simply:If you mean adding elements to the value of the dictionary a possible solution:
if you want to modify or update NSDictionary then first of all typecast it as NSMutableDictionary
then simply use
Swift 3+
Example to assign new values to Dictionary. You need to declare it as NSMutableDictionary:
Up till now the best way I have found to append data to a dictionary by using one of the higher order functions of Swift i.e. "reduce". Follow below code snippet:
@Dharmesh In your case, it will be,
Please let me know if you find any issues in using above syntax.
Dict.updateValue
updates value for existing key from dictionary or adds new new key-value pair if key does not exists.Example-
Result-