Remove values from dictionary in iOS swift

廉价感情. 提交于 2019-12-11 03:48:35

问题


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";
    });
}

And My Code:

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


回答1:


So use the NSMutableDictionary method removeObjectForKey. You will need to break out of your inner for loop when you delete an entry however.

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
            }
     }       
}



回答2:


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.)



来源:https://stackoverflow.com/questions/31613194/remove-values-from-dictionary-in-ios-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!