2017-05-11 198 views
0

下文提到的与键删除的NSMutableDictionary中的NSMutableArray是我的优惠券的数组,我想删除字典包含的“X”码如何迅速3

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

您可以使用'NSPredicate'获取包含'x'代码的'dictionary'。然后从数组中删除该对象。 @Rajat – iPeter

回答

1

首先,你为什么不尝试使用过他们的NS同行斯威夫特ArrayDictionary结构?这会让你的工作更加轻松,并期待您的代码更简洁:

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下载游乐场。

+0

跳过'NSPredicate',把条件放在块中。 – Willeke

-1

使用下面的代码试试,这可能会解决你的问题。任何澄清随时留下评论。 :)

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

有人可以告诉我我错在哪里,以便我可以纠正自己,永远不会给出任何错误的答案,将被放弃投票。请澄清。 :) – iPeter

+1

'array.filtered(using:pred)'不会编译。 'array.filtered(using:pred)'返回一个数组,而不是一个字典。我通常在发布答案之前亲自尝试代码。有时候甚至是好的问题和答案都会被降低。 – Willeke

+0

因此,如果我喜欢'let dict = array.filtered(using:pred)[0]',那会是正确的吗? @Willeke – iPeter