从字典数组中删除重复项,Swift 3 [英] Remove duplicates from array of dictionaries, Swift 3

查看:33
本文介绍了从字典数组中删除重复项,Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我有一个字典数组,如下所示:

I have an array of dictionaries as follows:

var arrayOfDicts = [
    ["Id":"01", "Name":"Alice", "Age":"15"]
    ["Id":"02", "Name":"Bob", "Age":"53"]
    ["Id":"03", "Name":"Cathy", "Age":"12"]
    ["Id":"04", "Name":"Bob", "Age":"83"]
    ["Id":"05", "Name":"Denise", "Age":"88"]
    ["Id":"06", "Name":"Alice", "Age":"44"]
]

我需要删除所有有重复名称的词典.例如,我需要一个输出:

I need to remove all dictionaries where there is a duplicate name. For instance, I need an output of:

var arrayOfDicts = [
    ["Id":"01", "Name":"Alice", "Age":"15"]
    ["Id":"02", "Name":"Bob", "Age":"53"]
    ["Id":"03", "Name":"Cathy", "Age":"12"]
    ["Id":"05", "Name":"Denise", "Age":"88"]
]

订单不需要保留.

尝试的解决方案

for i in 0..<arrayOfDicts.count
{
    let name1:String = arrayOfDicts[i]["Name"]

    for j in 0..<arrayOfDicts.count
    {
        let name2:String = arrayOfDicts[j]["Name"]

        if (i != j) && (name1 == name2)
        {
            arrayOfDicts.remove(j)
        }
    }
} 

虽然这会崩溃,但我相信因为我正在修改 arrayOfDicts 的大小,所以最终它 j 大于数组的大小.

This crashes though, I believe since I am modifying the size of arrayOfDicts, so eventually it j is larger than the size of the array.

如果有人能帮助我,那将不胜感激.

If someone could help me out, that would be much appreciated.

推荐答案

我绝对推荐使用新副本而不是修改初始数组.我还为已使用的名称创建了存储空间,因此您只需循环一次.

I definitely recommend having a new copy rather than modifying the initial array. I also create storage for names already used, so you should only need to loop once.

func noDuplicates(_ arrayOfDicts: [[String: String]]) -> [[String: String]] {
    var noDuplicates = [[String: String]]()
    var usedNames = [String]()
    for dict in arrayOfDicts {
        if let name = dict["name"], !usedNames.contains(name) {
            noDuplicates.append(dict)
            usedNames.append(name)
        }
    }
    return noDuplicates
}

这篇关于从字典数组中删除重复项,Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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