在iOS swift

时间:2015-07-24 14:30:03

标签: ios swift nsdictionary

我有一个JSON对象:

The Result {
    shops = ({
        date = "2015-07-22T14:14:48.867618";
        "num_items" = 0;
        score = "-1";
        "total_spend" = 0;
    },
    {
        date = "2015-07-22T14:17:03.713194";
        "num_items" = 1;
        score = 5;
        "total_spend" = "1.85";
    });
}

和我的代码:

let dict = result as! NSDictionary
var mutDict: NSMutableDictionary = dict.mutableCopy() as!     NSMutableDictionary

for (key, value) in mutDict {
    for i in 0..<backendArray.count {
        if value[i].objectForKey("num_items") === 0
            {
                //delete that shop only
            }
     }       
}

我想删除整个第一家商店及其所有内容,但不是第二家商店或商店。

我不想把它变成一个数组,因为我无法弄清楚如何将它变回来。数据需要仍然作为字典存储。感谢

2 个答案:

答案 0 :(得分:2)

字典中的键是shops,它有一个数组作为值。因此,您实际上并未从词典中删除带有num_items == 0的商店,而是从数组中删除(可能不是可变的)。因此,通过过滤旧数组来创建一个新数组,并更新字典中shops的值,例如:

dict["shops"] = (dict["shops"] as NSArray?)?.filter { (shop: Dictionary) in
    (shop["num_items"] as NSNumber?)?.integerValue > 0
}

(根据需要验证类型检查和强制转换;您提供的代码不是独立的,因此无法直接在操场上进行测试。)

答案 1 :(得分:2)

因此请使用NSMutableDictionary方法removeObjectForKey。但是,当您删除条目时,您将需要突破内部for循环。

let dict = result as! NSDictionary
var mutDict: NSMutableDictionary = dict.mutableCopy() as!     NSMutableDictionary

dictLoop: for (key, value) in mutDict {
    for i in 0..<backendArray.count {
        if value[i].objectForKey("num_items") === 0
            {
              //delete that shop only
              mutDict.removeObjectForKey(key)
              continue dictLoop
            }
     }       
}