How to append new data to an existing JSON array(swiftyJSON)
SwiftyJSON does not have append
or extend
functionality.
You can:
self.hoge = JSON(self.hoge.arrayObject! + JSON(data: newData).arrayObject!)
But I recommend to declare self.hoge
as [JSON]
var hoge:[JSON] = []
func readMoreData() {
let newData: NSData = ...
if let newArray = JSON(data:newData).array {
self.hoge += newArray
}
}
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"
}
}
}
You can use the merge
function for this.
https://github.com/SwiftyJSON/SwiftyJSON#merging
var array: JSON = [1, 2, 3]
array = try! array.merged(with: [4])
// -> [1, 2, 3, 4]