SwiftyJSON:从数组中删除所有对象

时间:2017-03-29 18:25:54

标签: swift swifty-json

我尝试使用removeAll()清除使用SwiftyJSON创建的数组中的所有项目,但它无法正常工作。我做错了什么?

let itemsArray = ["One", "Two"]
var jsonObject = JSON(itemsArray)
jsonObject.arrayObject?.removeAll()
let item = jsonObject.arrayValue

1 个答案:

答案 0 :(得分:2)

您无法修改JSON的数组:

解决方案

清理阵列的唯一选择:

jsonObject = JSON([String]())
//jsonObject = JSON([Any]())

完整样本

let itemsArray = ["One", "Two", "Three"]
var tempArray = itemsArray
var jsonObject = JSON(itemsArray)

let array: [String]? = []
jsonObject.arrayObject = array
print("===========================================")
print("Original array:\n\(jsonObject)")
//jsonObject = JSON([Any]())
jsonObject = JSON([String]())
print("Empty JSON array:\n\(jsonObject)")
print("===========================================")

// Not working
print("\nNot working exaple 1:")
jsonObject = JSON(itemsArray)
jsonObject.arrayObject?.removeAll()
print("JSON: jsonObject.arrayObject?.removeAll() = \n\(jsonObject)")
tempArray.removeAll()
print("!!! But [string].removeAll() = \(tempArray)")
print("===========================================")

print("\nNot working exaple 2:")
tempArray = itemsArray
for _ in 0..<jsonObject.arrayObject!.count {
    jsonObject.arrayObject!.removeLast()
    tempArray.removeLast()
}

print("JSON: for ... { jsonObject.arrayObject!.removeLast() } = \n\(jsonObject)")
print("!!! But [String]:for ...{ tempArray.removeLast() } = \(tempArray)")

结果

enter image description here