Swift 2-4
Another solution, using Extension
extension JSON{
mutating func appendIfArray(json:JSON){
if var arr = self.array{
arr.append(json)
self = JSON(arr);
}
}
mutating func appendIfDictionary(key:String,json:JSON){
if var dict = self.dictionary{
dict[key] = json;
self = JSON(dict);
}
}
}
Use:
var myJSON: JSON = [
"myDictionary": [String:AnyObject](),
"myArray" : [1,2,3,4]
]
myJSON["myDictionary"].appendIfDictionary(key:"A", json: JSON(["key1":"value1"]))
myJSON["myDictionary"].appendIfDictionary(key: "B", json: JSON(["key2":"value2"]))
myJSON["myArray"].appendIfArray(json: JSON(5))
print:
{
"myArray" : [
1,
2,
3,
4,
5
],
"myDictionary" : {
"B" : {
"key2" : "value2"
},
"A" : {
"key1" : "value1"
}
}
}