【问题标题】:How to remove duplicate from tuple如何从元组中删除重复项
【发布时间】:2016-09-21 08:07:19
【问题描述】:

我正在获取一个 json 数据并将其附加到一个元组中,这个数组中有重复项有没有办法可以删除它们?这是获取 json 数据并将其设置为元组的方法

 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)")

      }

【问题讨论】:

  • 这是一个元组
  • 我刚刚检查过:/ 遗憾的是 tuple 不是一个对象,不适用于 AnyObject,所以你不能将它转换为 Set 或 NSSet,我认为 tuples 的功能非常有限,所以我建议你改变使用 Struct 或 Class 会更好,将其重构为 Struct 如下提供的答案
  • 你有一个元组数组 (resultTuples?),所以技术是一样的。
  • 好的@Tj3n 我想我会是一个普通的数组

标签: ios swift uitableview tuples


【解决方案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))

请注意,在这种情况下,您会丢失原始排序顺序。

【讨论】:

  • @lordxx:有什么问题?
  • 好的,所以当我尝试使用数组时它没有工作,我更新了问题
【解决方案2】:

您可以在插入之前使用以下函数检查元组是否包含在特定数组中:

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?

【讨论】:

    猜你喜欢
    • 2019-03-29
    • 2021-03-09
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2022-01-03
    • 2019-03-07
    • 2012-10-04
    相关资源
    最近更新 更多