gpt4 book ai didi

ios - 添加字典时避免重复

转载 作者:行者123 更新时间:2023-11-30 12:01:28 26 4
gpt4 key购买 nike

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

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

我将这些值添加到数组中,如下所示......

self.arrayOfDictionary.append(mydictionary)

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

这里的基本思想是将 Collection View 项中的数据添加到字典数组中。当我单击每个 Collection View 项上的按钮时,其上的数据将添加到字典数组中。同时在 TableView 单元格中显示这些数据。但是,当我从 tableview 返回并再次访问 collectionview 项目并单击其他一些 collecn.view 项目,以便像以前一样将它们添加到字典数组中时,最初添加到字典数组中的项目会得到再次添加。必须以某种方式阻止这种情况。

正如另一位 SO 用户所建议的那样,尝试了类似的方法来防止这种重复......

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

但这似乎不起作用。这样,数组中就没有添加任何内容,并且它完全是空的。希望有人能帮忙...

最佳答案

尝试使用此代码以避免重复

我希望“id”值在您的字典中是唯一的。

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

关于ios - 添加字典时避免重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47159179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com