Append to array in [String: Any] dictionary structure
If you prefer brevity over clarity, you can perform this operation in a single line, making use of the nil
coalescing operator and the +
operator for RangeReplaceableCollection
(to which Array
conforms), the latter used for the "append" step (in fact constructing a new collection which will the replace the existing one when replacing the value of data["items"]
).
// example setup
var data: [String: Any] = [
"key1": "example value 1",
"key2": "example value 2",
"items": []
]
// copy-mutate-replace the "items" array inline, adding a new dictionary
data["items"] = (data["items"] as? [[String: Any]] ?? []) + [["key": "new value"]]
print(data)
/* ["key2": "example value 2",
"items": [["key": "new value"]],
"key1": "example value 1"] */
// add another dictionary to the "items" array
data["items"] = (data["items"] as? [[String: Any]] ?? []) + [["key": "new value"]]
print(data)
/* ["key2": "example value 2",
"items": [["key": "new value"], ["key": "new value"]],
"key1": "example value 1"] */
The type of data[Items]
isn't Array
but actually Array<[String: Any]>
.
You could probably squeeze this into fewer steps, but I prefer the clarity of multiple steps:
var data: [String: Any] = [
"key1": "example value 1",
"key2": "example value 2",
"items": []
]
for index in 1...3 {
let item: [String: Any] = [
"key": "new value"
]
// get existing items, or create new array if doesn't exist
var existingItems = data["items"] as? [[String: Any]] ?? [[String: Any]]()
// append the item
existingItems.append(item)
// replace back into `data`
data["items"] = existingItems
}