Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append elements into a dictionary in Swift?

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?

like image 409
Dharmesh Kheni Avatar asked Oct 09 '22 07:10

Dharmesh Kheni


People also ask

What is Nsdictionary?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.


2 Answers

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.

like image 282
Antonio Avatar answered Oct 10 '22 21:10

Antonio


you can add using the following way and change Dictionary to NSMutableDictionary

dict["key"] = "value"
like image 136
yashwanth77 Avatar answered Oct 10 '22 20:10

yashwanth77