How to append elements into dictionary in swift?

2019-01-13 04:43发布

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?

13条回答
走好不送
2楼-- · 2019-01-13 05:33

Given two dictionaries as below:

var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]

Here is how you can add all the items from dic2 to dic1:

dic2.map {
   dic1[$0.0] = $0.1
}

Cheers A.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-13 05:36

You can use another tester class to set dictionary value like

variableValue["X"] = 3.14

In above variableValue is a dictionary created by another class. You set key:value.

查看更多
相关推荐>>
4楼-- · 2019-01-13 05:37

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.

查看更多
我想做一个坏孩纸
5楼-- · 2019-01-13 05:39

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

dict["key"] = "value"
查看更多
Explosion°爆炸
6楼-- · 2019-01-13 05:43

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 :

var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
查看更多
乱世女痞
7楼-- · 2019-01-13 05:46

In Swift, if you are using NSDictionary, you can use setValue:

dict.setValue("value", forKey: "key")
查看更多
登录 后发表回答