如何在NSArray中附加到NSMutableDictionary?

时间:2015-06-12 18:56:38

标签: ios swift

通过以下方式从JSON文件中提取集合:

if let collection = dictionary!.objectForKey("collection") as? NSMutableArray

以下不起作用:

for item in collection as! [NSMutableDictionary]
{
    // mutating method sent to immutable object
    item["row"] = 1
}

JSON:

{
    "collection":
    [
        {
            "row": 1,
            "col": 0
        },
        {
            "row": 1,
            "col": 1
        },
        {
            "row": 2,
            "col": 0
        }
    ]
}

1 个答案:

答案 0 :(得分:2)

您生成的JSON对象应该使用可变容器构建,并且您还需要将该集合转换为可变的。

let json = "{\"collection\":[{\"row\": 1,\"col\": 0},{\"row\": 1,\"col\": 1},{\"row\": 2,\"col\": 0}]}"
if let
    jsonData = json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false),
    dictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSMutableDictionary {

    if let collection = dictionary["collection"] as? NSMutableArray {
        for i in stride(from: 0, to: collection.count, by: 1) {
            (collection[i] as! NSMutableDictionary)["row"] = 1
        }

    }

}

您可能还想考虑像SwiftyJSON

这样的JSON库