How to append elements into a dictionary in Swift?

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

    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.

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

    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)
    
    0 讨论(0)
  • 2020-11-29 00:00

    I added Dictionary extension

    extension Dictionary {   
      func cloneWith(_ dict: [Key: Value]) -> [Key: Value] {
        var result = self
        dict.forEach { key, value in result[key] = value }
        return result  
      }
    }
    

    you can use cloneWith like this

     newDictionary = dict.reduce([3 : "efg"]) { r, e in r.cloneWith(e) }
    
    0 讨论(0)
  • 2020-11-29 00:01
    var dict = ["name": "Samira", "surname": "Sami"]
    // Add a new enter code herekey with a value
    dict["email"] = "sample@email.com"
    print(dict)
    
    0 讨论(0)
  • 2020-11-29 00:03

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

    dict["key"] = "value"
    
    0 讨论(0)
  • 2020-11-29 00:03

    There is no function to append the data in dictionary. You just assign the value against new key in existing dictionary. it will automatically add value to the dictionary.

    var param  = ["Name":"Aloha","user" : "Aloha 2"]
    param["questions"] = "Are you mine?"
    print(param)
    

    The output will be like

    ["Name":"Aloha","user" : "Aloha 2","questions" : ""Are you mine"?"]

    0 讨论(0)
提交回复
热议问题