How to append elements into a dictionary in Swift?

后端 未结 19 1974
旧时难觅i
旧时难觅i 2020-11-28 23:31

I have a simple Dictionary which is defined like:

var dict : NSDictionary = [ 1 : \"abc\", 2 : \"cde\"]

Now I want to add an element into t

19条回答
  •  臣服心动
    2020-11-28 23:54

    As of Swift 5, the following code collection works.

     // main dict to start with
     var myDict : Dictionary = [ 1 : "abc", 2 : "cde"]
    
     // dict(s) to be added to main dict
     let myDictToMergeWith : Dictionary = [ 5 : "l m n"]
     let myDictUpdated : Dictionary = [ 5 : "lmn"]
     let myDictToBeMapped : Dictionary = [ 6 : "opq"]
    
     myDict[3]="fgh"
     myDict.updateValue("ijk", forKey: 4)
    
     myDict.merge(myDictToMergeWith){(current, _) in current}
     print(myDict)
    
     myDict.merge(myDictUpdated){(_, new) in new}
     print(myDict)
    
     myDictToBeMapped.map {
         myDict[$0.0] = $0.1
     }
     print(myDict)
    

提交回复
热议问题