How to append elements into a dictionary in Swift?

后端 未结 19 1926
旧时难觅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:51

    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)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-28 23:56

    To add new elements just set:

    listParrameters["your parrameter"] = value
    
    0 讨论(0)
  • 2020-11-28 23:58

    [String:Any]

    For the fellows using [String:Any] instead of Dictionary below is the extension

    extension Dictionary where Key == String, Value == Any {
        
        mutating func append(anotherDict:[String:Any]) {
            for (key, value) in anotherDict {
                self.updateValue(value, forKey: key)
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 23:58

    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.

    0 讨论(0)
  • 2020-11-28 23:59

    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)
    
    0 讨论(0)
提交回复
热议问题