Reputation: 25
I am getting a json data and appending it to a tuple there are duplicates in this array is there a way i can remove them? here is how am getting the json data and setting it to the tupple
if let hru = ($0["Menu"]["title"]).string{
let uw = ($0["name"]).string
let tagloc = (tag: hru, location: uw)
self.resultTuples.append(tagloc)
}
Am printing the tuple like this
for var i = 0; i < self.resultTuples.count; ++i{
print(self.resultTuples[i])
}
But what gets printed is
tag: Rice Dishes
tag: Rice Dishes
tag: Cakes and Creams
tag: Cakes and Creams
tag: Cakes and Creams
tag: Pastries and Others
tag: Pastries and Others
tag: Pastries and Others
tag: Pastries and Others
tag: Pastries and Others
tag: Pastries and Others
tag: Pastries and Others
tag: Pastries and Others
tag: Pastries and Others
tag: Pastries and Others
tag: Soups and Sauces
tag: Soups and Sauces
....
I want to remove all the duplicates from this tuple
EDIT:
Using array did not work i have a model Menus
if let hru = ($0["Menu"]["title"]).string{
var men = Menus(nam: hru)
let set = NSSet(array: self.menus)
self.menus = set.allObjects as! [Menus]
self.menus.append(men)
}
for i in self.menus{
print("MENUSS \(i.name)")
}
Upvotes: 2
Views: 848
Reputation: 59496
If you use a model value like a struct instead of a tuple
struct TagAndLocation: Hashable {
let tag: String
let location: String
var hashValue: Int { return tag.hashValue }
}
func ==(left:TagAndLocation, right: TagAndLocation) -> Bool {
return left.tag == right.tag && left.location == right.location
}
You can leverage the Set
functionalities to remove duplicates
let results: [TagAndLocation] = ...
let uniqueResults = Array(Set(results))
Please note that in this case you lose the original sort order.
Upvotes: 4
Reputation: 362
You could check if a tuple is contained in a specific array before the insertion with the following function:
func containsTuple(arr: [(String, String)], tup:(String, String)) -> Bool {
let (c1, c2) = tup
for (v1, v2) in arr {
if v1 == c1 && v2 == c2 {
return true
}
}
return false
}
More info here How do I check if an array of tuples contains a particular one in Swift?
Upvotes: 0