Swift 3.0删除字典数组中的重复项 [英] Swift 3.0 Remove duplicates in Array of Dictionaries

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

问题描述

我正在努力在Swift 3.0中删除字典数组中的重复字典

I am working removing the duplicate Dictionaries in an array of Dictionaries in swift 3.0

下面是

let Dict1 : [String : String] = ["messageTo":"Madhu"]
let Dict2 : [String : String] = ["messageTo":"Kiran"]
let Dict3 : [String : String] = ["messageTo":"Raju"]

var arrOfDict = [[String:String]]()
arrOfDict.append(Dict1)
arrOfDict.append(Dict2)
arrOfDict.append(Dict1)
arrOfDict.append(Dict3)
arrOfDict.append(Dict2
print(arrOfDict)

//prints [["messageTo": "Madhu"], ["messageTo": "Kiran"], ["messageTo": "Madhu"], ["messageTo": "Raju"], ["messageTo": "Kiran"]]

如您所见,arrOfDict中有两个重复的字典.

As you can see there are 2 duplicate dictionaries in the arrOfDict.

有谁能帮助我使用 Set 或其他任何方法

can any one help me out in filtering the duplicates using Set or any other approach

推荐答案

字典不符合Hashable(或Equatable),因此在这种情况下不能使用Set.但是,对于KeyValue类型为Equatable的字典,我们可以访问==运算符以方便地对字典数组执行唯一性过滤:

Dictionaries does not conform to Hashable (or Equatable), so using Set is not an available approach in this case. For dictionaries where Key and Value types are Equatable, however, we have access to the == operator for readily performing a uniqueness filtering of the array of dictionaries:

public func ==<Key : Equatable, Value : Equatable>(
            lhs: [Key : Value], rhs: [Key : Value]) -> Bool

例如如下(O(n^2))

arrOfDict = arrOfDict.enumerated()
    .filter { (idx, dict) in !arrOfDict[0..<idx].contains(where: {$0 == dict}) }
    .map { $1 }

print(arrOfDict)
// [["messageTo": "Madhu"], ["messageTo": "Kiran"], ["messageTo": "Raju"]]

// or ...
arrOfDict = arrOfDict.enumerated()
    .flatMap { (idx, dict) in !arrOfDict[0..<idx].contains(where: {$0 == dict}) ? dict : nil }

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

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