Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

ios - Avoid duplicates while adding in dictionary

I have a dictionary in which I'm adding values like so...

var mydictionary = ["id": "", "quantity": "","sellingPrice":""] as [String : Any]
    dictionary["id"] = product?.id
    dictionary["quantity"] = product?.quantity
    dictionary["sellingPrice"] = product?.theRate

And these values I added to an array like so...

self.arrayOfDictionary.append(mydictionary)

But if arrayOfDictionary already contains mydictionary, I don't want to add it. Else, I want to add it.

The basic idea here is to add data from collection view items to array of dictionary. When I click on the buttons that I have on each collection view item the data on it is added to an array of dict. while at the same time showing those data in a tableviewcell. But when I navigate back from the tableview & visit the collectionview items again and click on some other collecn.view item, so as to add them to the array of dictionary as before, then the item that was added initially to the array of dictionary gets added again. This has to be somehow prevented.

As suggested by another SO user something like this was tried to prevent this duplication...

    if self.arrayOfDictionary.contains(where: { (dict) -> Bool in
        "(dict["id"] ?? "")" != "(dictionary["id"] ?? "")"}) {
        self.arrayOfDictionary.append(dictionary)
    }

But this doesn't seem to work. With this nothing is added to the array and its totally empty. Hope somebody can help...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this code to avoid duplication

I hope "id" value will be unique in your dictionary.

    var mydictionary = ["id": "1", "quantity": "","sellingPrice":""] as [String : Any]

    var arrayOfDictionary = [Dictionary<String, Any>]() //declare this globally
    let arrValue = arrayOfDictionary.filter{ (($0["id"]!) as! String).range(of: mydictionary["id"]! as! String, options: [.diacriticInsensitive, .caseInsensitive]) != nil }
    if arrValue.count == 0 {

        arrayOfDictionary.append(mydictionary)
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...