下文提到的与键删除的NSMutableDictionary中的NSMutableArray是我的优惠券的数组,我想删除字典包含的“X”码如何迅速3
(
{
"coupon_code" = FLAT20PERCENT;
}
{
“coupon_code” = FLAT5PERCENT;
}
{
“coupon_code” = FLAT50;
}
)
下文提到的与键删除的NSMutableDictionary中的NSMutableArray是我的优惠券的数组,我想删除字典包含的“X”码如何迅速3
(
{
"coupon_code" = FLAT20PERCENT;
}
{
“coupon_code” = FLAT5PERCENT;
}
{
“coupon_code” = FLAT50;
}
)
首先,你为什么不尝试使用过他们的NS
同行斯威夫特Array
和Dictionary
结构?这会让你的工作更加轻松,并期待您的代码更简洁:
Objective-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)
您可以从here下载游乐场。
跳过'NSPredicate',把条件放在块中。 – Willeke
使用下面的代码试试,这可能会解决你的问题。任何澄清随时留下评论。 :)
//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)
您可以使用'NSPredicate'获取包含'x'代码的'dictionary'。然后从数组中删除该对象。 @Rajat – iPeter