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?
Given two dictionaries as below:
Here is how you can add all the items from dic2 to dic1:
Cheers A.
You can use another tester class to set dictionary value like
In above
variableValue
is a dictionary created by another class. You setkey:value
.You're using
NSDictionary
. Unless you explicitly need it to be that type for some reason, I recommend using a Swift dictionary.You can pass a Swift dictionary to any function expecting
NSDictionary
without any extra work, becauseDictionary<>
andNSDictionary
seamlessly bridge to each other. The advantage of the native Swift way is that the dictionary uses generic types, so if you define it withInt
as the key andString
as the value, you cannot mistakenly use keys and values of different types. (The compiler checks the types on your behalf.)Based on what I see in your code, your dictionary uses
Int
as the key andString
as the value. To create an instance and add an item at a later time you can use this code:If you later need to assign it to a variable of
NSDictionary
type, just do an explicit cast:And, as mentioned earlier, if you want to pass it to a function expecting
NSDictionary
, pass it as-is without any cast or conversion.you can add using the following way and change
Dictionary
toNSMutableDictionary
I know this might be coming very late, but it may prove useful to someone. So for appending key value pairs to dictionaries in swift, you can use updateValue(value: , forKey: ) method as follows :
In Swift, if you are using NSDictionary, you can use
setValue
: