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



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

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

首先,为什么不尝试使用 Swift 的 ArrayDictionary 结构而不是它们的NS对应结构呢?这将使您的工作更加轻松,并且您的代码看起来更简洁:

目标C方式:

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

快速方式:

(另外,您不会丢失与上述类型不同的类型。

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)

你可以从这里下载游乐场。

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

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

最新更新