0

Given this

var applicationPayload =
    [
        "main": [
            "key1": "value1",
            "key2": [
                "inside1": "insideValue1"
            ]
        ]
    ]

How can I append or add something inside key2 property.. I'd like the result to be something like this

[
    "main": [
        "key1": "value1",
        "key2": [
            "newInside2": "newInsideValue2",
            "inside1": "insideValue1"
        ]
    ]
]

I tried doing this does not seems to work

applicationPayload["main"]["key2"]["newInside2"] = "newInsideValue2"
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
Harts
  • 4,023
  • 9
  • 54
  • 93
  • There are a lot of similar questions, for example [this one](https://stackoverflow.com/questions/25475463/how-to-access-deeply-nested-dictionaries-in-swift). Main thing you need to know is that nested value lookup yields an optional constant by default. To make sure Xcode suggests possible code completion and to keep things clear make sure you declare a concrete type for the dictionary variable, such as `[String: [String: [String: String]]]`. – ermik Jun 25 '19 at 22:56
  • To avoid making code unnecessarily complex and error-prone — access the key you need and write it to a variable, then add necessary variables and write it back to the original dictionary. – ermik Jun 25 '19 at 22:56

2 Answers2

0

You can try for easy access/assign with keyPath

   // get value of key2
 var res = applicationPayload[keyPath:"main.key2"] as! [String:Any]
   // add the other key
 res["newInside2"] = "newInsideValue2"
   // mutate key2
 applicationPayload[keyPath:"main.key2"] = res

For more about keypaths check https://oleb.net/blog/2017/01/dictionary-key-paths/

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

You could create a variable containing the current value of key2 and modify that before rewriting it back into the original dictionary:

import Foundation

var applicationPayload =
    [
        "main": [
            "key1": "value1",
            "key2": [
                "inside1": "insideValue1"
            ]
        ]
    ]

print("Before: \(applicationPayload)")

var key2Value = applicationPayload["main"]?["key2"] as! [String: String]
key2Value["newInside2"] = "newInsideValue2"
applicationPayload["main"]?["key2"] = key2Value

print("After: \(applicationPayload)")

Output:

Before: ["main": ["key1": "value1", "key2": ["inside1": "insideValue1"]]]
After: ["main": ["key1": "value1", "key2": ["inside1": "insideValue1", "newInside2": "newInsideValue2"]]]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40