Search code examples
swiftnsmutablearraynsmutabledictionary

How to delete NSMutableDictionary with key in NSMutableArray in swift 3


Below mentioned is my array of coupons and I want to delete dictionary which contains 'x' code

    (
        {
        "coupon_code" = FLAT20PERCENT;
    }
       {
       “coupon_code” = FLAT5PERCENT;
    }
       {
      “coupon_code” = FLAT50;
    }
   )

Solution

  • First off, why don't you try using Swift's Array and Dictionary structures over their NS counterparts? This will make your job much easier and look your code more concise:

    Objective-C way:

    let array = NSMutableArray(array: [
      NSMutableDictionary(dictionary: ["coupon_code": "FLAT50PERCENT"]),
      NSMutableDictionary(dictionary: ["coupon_code": "FLAT5PERCENT"]),
      NSMutableDictionary(dictionary: ["coupon_code": "FLAT50"])
    ])
    

    Swift way:

    (Plus, you don't lose the type unlike above.)

    var array = [
      ["coupon_code": "FLAT50PERCENT"],
      ["coupon_code": "FLAT5PERCENT"],
      ["coupon_code": "FLAT50"]
    ]
    

    Anyway, if you insist on using collection classes from Objective-C, here is one way of doing that:

    let searchString = "PERCENT"
    let predicate = NSPredicate(format: "coupon_code contains[cd] %@", searchString)
    // change it to "coupon_code == @" for checking equality.
    
    let indexes = array.indexesOfObjects(options: []) { (dictionary, index, stop) -> Bool in
      return predicate.evaluate(with: dictionary)
    }
    array.removeObjects(at: indexes)
    

    You can download the playground from here.