kernelpanic kernelpanic - 1 year ago 85
Swift Question

Swift JSON add new key to existing dictionary

I'm using Alamofire and SwiftyJSON to get and manage data from an API
After making my initial request I end up with nested collection of type JSON

According to SwiftyJSON I can loop through data like so

for (key: String, subJson: JSON) in json {
//Do something you want

Again, according to SwiftyJSON I should be able to set new values like so:

json["name"] = JSON("new-name")

I have a nested collection of data and I can dig in as deep as I want, but I'm unable to alter the object and set new key:value pair. How would I got about doing this in Swift?

Here's my code :

for (key: String, stop: JSON) in stops {
var physicalStops = stop["physicalStops"]
for (key: String, physicalStop: JSON) in physicalStops {
println("Prints out \(physicalStop) just fine")
// physicalStop["myNewkey"] = "Somevalue" // DOES NOT WORK (@lvalue is not identical to 'JSON)
// physicalStop["myNewkey"] = JSON("Somevalue") //SAME Story

Basically I'd like to keep the very same structure of the original JSON object, but add additional key:value on the second level nesting for each sub object.

Answer Source

First, you can use var in for-loop to make value modifiable inside the loop. However, JSON is struct so it behaves as a value type, so in your nested example, you have to reassign also the child JSON to the parent JSON otherwise it just modifies the value inside the loop but not in the original structure

var json: JSON = ["foo": ["amount": 2], "bar": ["amount": 3]]
for (key: String, var item: JSON) in json {
     println("\(key) -> \(item)")
     item["price"] = 10
     json[key] = item
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download