I have a simple Dictionary which is defined like:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
Now I want to add an element into this dictionary: 3 : "efg"
How can I append 3 : "efg"
into this existing dictionary?
An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.
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, because Dictionary<>
and NSDictionary
seamlessly bridge to each other. The advantage of the native Swift way is that the dictionary uses generic types, so if you define it with Int
as the key and String
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 and String
as the value. To create an instance and add an item at a later time you can use this code:
var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"
If you later need to assign it to a variable of NSDictionary
type, just do an explicit cast:
let nsDict = dict as! NSDictionary
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
to NSMutableDictionary
dict["key"] = "value"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With