我正在获取一个json数据并将其附加到一个元组,这个数组中有重复项是否有一种方法可以删除它们?这里是如何获取json数据并将其设置为tupple
if let hru = ($0["Menu"]["title"]).string{
let uw = ($0["name"]).string
let tagloc = (tag: hru, location: uw)
self.resultTuples.append(tagloc)
}
打印这样的元组
for var i = 0; i < self.resultTuples.count; ++i{
print(self.resultTuples[i])
}
但打印的内容是
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
....
我想删除此元组中的所有重复项
编辑:
使用数组不起作用我有一个模型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)")
}
答案 0 :(得分:1)
如果使用类似结构的模型值而不是元组
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
}
您可以利用Set
功能删除重复项
let results: [TagAndLocation] = ...
let uniqueResults = Array(Set(results))
请注意,在这种情况下,您将丢失原始排序顺序。
答案 1 :(得分:0)
在使用以下函数插入之前,您可以检查特定数组中是否包含元组:
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
}
此处有更多信息How do I check if an array of tuples contains a particular one in Swift?