I am working removing the duplicate Dictionaries in an array of Dictionaries in swift 3.0
The below is the
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"]]
As you can see there are 2 duplicate dictionaries in the arrOfDict.
can any one help me out in filtering the duplicates using Set or any other approach
Dictionaries does not conform to
Hashable
(orEquatable
), so usingSet
is not an available approach in this case. For dictionaries whereKey
andValue
types areEquatable
, however, we have access to the==
operator for readily performing a uniqueness filtering of the array of dictionaries:E.g. as follows (
O(n^2)
)you can try this :
The reason why it is duplicated, because you add
Dict1
andDict2
2 times. May i ask why?Set
would not work for you, becauseDictionary
type does not conform to theHashable
protocol, only itskey
property.You can do a validation on the dictionary, if there is already a value like that, do not append it to
arrOfDict
.