HannahCarney
HannahCarney

Reputation: 3631

Remove values from dictionary in iOS swift

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

Upvotes: 2

Views: 11188

Answers (2)

Arkku
Arkku

Reputation: 42129

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

Upvotes: 2

Duncan C
Duncan C

Reputation: 131418

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

Upvotes: 2

Related Questions