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:21

If your dictionary is Int to String you can do simply:

dict[3] = "efg"

If you mean adding elements to the value of the dictionary a possible solution:

var dict = Dictionary<String, Array<Int>>()

dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)
查看更多
▲ chillily
3楼-- · 2019-01-13 05:21

if you want to modify or update NSDictionary then first of all typecast it as NSMutableDictionary

let newdictionary = NSDictionary as NSMutableDictionary

then simply use

 newdictionary.setValue(value: AnyObject?, forKey: String)
查看更多
冷血范
4楼-- · 2019-01-13 05:22

Swift 3+

Example to assign new values to Dictionary. You need to declare it as NSMutableDictionary:

var myDictionary: NSMutableDictionary = [:]
let newValue = 1
myDictionary["newKey"] = newValue
print(myDictionary)
查看更多
Summer. ? 凉城
5楼-- · 2019-01-13 05:24

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:

newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }

@Dharmesh In your case, it will be,

newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }

Please let me know if you find any issues in using above syntax.

查看更多
Fickle 薄情
6楼-- · 2019-01-13 05:25
var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "sample@email.com"
print(dict)
查看更多
Fickle 薄情
7楼-- · 2019-01-13 05:31

Dict.updateValue updates value for existing key from dictionary or adds new new key-value pair if key does not exists.

Example-

var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")

Result-

▿  : 2 elements
    - key : "userId"
    - value : 866
▿  : 2 elements
    - key : "otherNotes"
    - value : "Hello"
查看更多
登录 后发表回答