如何在swift 3中删除NSMUTABLEARRY中带有键的NSMutableDictionary
下面提到的是我的优惠券数组,我想删除包含“x”代码的字典如何在swift 3中删除NSMUTABLEARRY中带有键的NSMutableDictionary,swift,nsmutablearray,nsmutabledictionary,Swift,Nsmutablearray,Nsmutabledictionary,下面提到的是我的优惠券数组,我想删除包含“x”代码的字典 ( { "coupon_code" = FLAT20PERCENT; } { “coupon_code” = FLAT5PERCENT; } { “coupon_code” = FLAT50; } ) 尝试使用下面的代码,这可能会解决您的问题。如需任何澄清,请随时发表评论。:) 首先,为什么不尝试在对应的NS上使用
(
{
"coupon_code" = FLAT20PERCENT;
}
{
“coupon_code” = FLAT5PERCENT;
}
{
“coupon_code” = FLAT50;
}
)
尝试使用下面的代码,这可能会解决您的问题。如需任何澄清,请随时发表评论。:)
首先,为什么不尝试在对应的
NS
上使用Swift和结构?这将使您的工作更轻松,代码看起来更简洁:
目标C方式:
let array = NSMutableArray(array: [
NSMutableDictionary(dictionary: ["coupon_code": "FLAT50PERCENT"]),
NSMutableDictionary(dictionary: ["coupon_code": "FLAT5PERCENT"]),
NSMutableDictionary(dictionary: ["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)
您可以从下载游乐场。您可以使用
NSPredicate
获取包含“x”代码的词典。然后从数组中删除该对象@Rajat跳过预测
,把条件放在块中。有人能告诉我哪里错了,这样我就可以纠正自己,永远不会给出任何会被否决的错误答案。请澄清:)<代码>数组。已筛选(使用:pred)将不会编译<代码>数组。筛选(使用:pred)返回数组,而不是字典。在发布答案之前,我通常会自己尝试代码。有时甚至好的问题和答案也会被否决。所以,如果我喜欢让dict=array.filtered(使用:pred)[0]
,这是否正确@维勒克
var array = [
["coupon_code": "FLAT50PERCENT"],
["coupon_code": "FLAT5PERCENT"],
["coupon_code": "FLAT50"]
]
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)