Home > front end >  How to update or add value in nested dictionary swift?
How to update or add value in nested dictionary swift?

Time:08-01

 var dataDictionary = Dictionary<String, Any>()

     dataDictionary = [
             "reference": "",
             "country": "",
             "language": "EN",
                      ]
     dataDictionary["innerObject"] = [
                 "name": "",
                 "middle_name" : "",
                 "address" : "",
             ]

Based on some scenario I want to add some keys on inner object. How can I add or modify them. Any help would be appreciated.

CodePudding user response:

You can update the dictionary value like this

 var dataDictionary = Dictionary<String, Any>()
 dataDictionary = [
        "reference": "",
        "country": "",
        "language": "EN",
    ]
    dataDictionary["innerObject"] = [
        "name": "",
        "middle_name" : "",
        "address" : "",
    ]
    
    var obj = dataDictionary["innerObject"] as! [String: Any]
    obj["name"] = "Your name"
    dataDictionary["innerObject"] = obj


   print(dataDictionary) //["reference": "", "language": "EN", "country": "", "innerObject": ["name": "Your name", "address": "", "middle_name": ""]]
  • Related