从iOS swift中的字典中删除值 [英] Remove values from dictionary in iOS swift
问题描述
我有一个这样的 JSON 对象:
I have a JSON object as such:
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
}
}
}
我想删除整个第一家商店及其所有内容,但不想删除第二家商店或商店.
I want to delete the whole first shop and all of it's contents, but not the second shop or the shops.
我不想把它变成一个数组,因为我不知道如何把它转回来.数据需要仍然存储为字典.谢谢
I don't want to turn it into an Array, because I can't figure out how to turn it back. Data needs to be stored still as a Dictionary. Thanks
推荐答案
字典中的键是shops
,它有一个数组作为值.因此,您实际上并没有从 dictionary 中删除带有 num_items == 0
的商店,而是从数组(可能不可变)中删除.因此,通过过滤旧数组创建一个新数组,并更新字典中 shops
的值,例如:
The key in the dictionary is shops
, and it has an array as value. So you are not actually deleting the shops with num_items == 0
from the dictionary but from the array (which is probably not mutable). So create a new array by filtering the old one, and update the value for shops
in dictionary, e.g.:
dict["shops"] = (dict["shops"] as NSArray?)?.filter { (shop: Dictionary) in
(shop["num_items"] as NSNumber?)?.integerValue > 0
}
(根据需要验证类型检查和强制转换;您提供的代码不是独立的,因此无法直接在操场上进行测试.)
(Verify type checks and casts as necessary; the code you gave is not stand-alone so can't test directly in a playground.)
这篇关于从iOS swift中的字典中删除值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!