在添加字典时避免重复 [英] Avoid duplicates while adding in dictionary

查看:111
本文介绍了在添加字典时避免重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,其中像这样添加值...

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)

但是,如果arrayOfDictionary已经包含mydictionary,则我不想添加它.否则,我要添加它.

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

这里的基本思想是将集合视图项中的数据添加到字典数组中.当我单击每个集合视图项上的按钮时,其上的数据将添加到字典数组中.同时在tableviewcell中显示这些数据.但是,当我从tableview&再次访问collectionview项,然后单击其他collecn.view项,以便像以前一样将其添加到字典数组中,然后再次添加最初添加到字典数组中的项.必须以某种方式防止这种情况.

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.

正如另一位SO用户所建议的那样,试图防止这种重复...

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...

推荐答案

尝试使用此代码避免重复

Try this code to avoid duplication

我希望"id"值在您的字典中是唯一的.

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

这篇关于在添加字典时避免重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆