如何在 swift 3 中使用 NSMutableArray 中的键删除 NSMutableDictionary

How to delete NSMutableDictionary with key in NSMutableArray in swift 3

下面提到的是我的优惠券数组,我想删除包含 'x' 代码的字典

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

尝试使用以下代码,这可能会解决您的问题。如需任何说明,请随时发表评论。 :)

    //Creating an `NsPredicate` that helps to find out the dictionary which contains 'x' code.
    let pred = NSPredicate(format: "coupon_code == %@", x)

    //Filtering your array with the pred to get that Dictionary.
    let dict = array .filtered(using: pred)

    //Deleting that object from your array.
    array .removeObject(identicalTo: dict)

首先,您为什么不尝试使用 Swift 的 Array and Dictionary 结构而不是 NS 的对应结构?这将使您的工作更轻松,代码看起来更简洁:

Objective-C方式:

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

Swift方式:

(此外,您不会丢失与上面不同的类型。)

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

无论如何,如果您坚持使用 Objective-C 中的集合 类,这里有一种方法:

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)

您可以从 here 下载 playground。