查找并删除自定义数组类型中的重复项

时间:2016-11-16 20:51:58

标签: arrays swift duplicates swift3

我有以下类,基于节点/键组合:

class cellData {
   let nodeText : String
   let keyText : String

   init(nodeText: String, keyText: String) {
      self.nodeText = nodeText
      self.keyText = keyText
   }

   var desription: String { return "<Node; name: \(nodeText); key; \(keyText)>" }
}

基于上面的类,我创建了两组:

var firstSetData = [cellData]()
var secondSetData = [cellData]()

firstSetData = [cellData(nodeText: "a", keyText: "1"),
                cellData(nodeText: "a", keyText: "2"),
                cellData(nodeText: "c", keyText: "42")]

 secondSetData = [cellData(nodeText: "a", keyText: "1"),
                  cellData(nodeText: "b", keyText: "100"),
                  cellData(nodeText: "c", keyText: "2"),
                  cellData(nodeText: "d", keyText: "1")]

我需要一个函数来返回第3组类&#34; cellData&#34;,但只有一个相同节点/键组合的唯一实例。这意味着我的最终设置必须如下所示:

finalSet = [cellData(nodeText: "a", keyText: "1"),
            cellData(nodeText: "a", keyText: "2"),
            cellData(nodeText: "b", keyText: "100"),
            cellData(nodeText: "c", keyText: "2"),
            cellData(nodeText: "c", keyText: "42")]        
            cellData(nodeText: "d", keyText: "1")]

我尝试过类似的东西,但它并不起作用:

for node in combinedSetData {
    if (combinedSetData.filter({$0.nodeText == node.nodeText && $0.keyText == node.keyText})).count > 1 {
     // remove duplicate elements and append to new set      
     }

 }
如果可能的话,最好选择Swift 3。提前谢谢!

2 个答案:

答案 0 :(得分:0)

首先,让您的cellData课程符合Equatable

class cellData : Equatable { 
   static func ==(lhs: cellData, rhs: cellData) -> Bool {
        return lhs.nodeText == rhs.nodeText && lhs.keyText == rhs.keyText
    }

    // ...
}

然后构建finalSetData很简单:

var finalSetData = [cellData]()
(firstSetData + secondSetData).forEach {
    if !finalSetData.contains($0) {
        finalSetData.append($0)
    }
}

// To match the order in your example...
finalSetData.sort {
    if $0.nodeText != $1.nodeText {
        return $0.nodeText < $1.nodeText
    } else {
        return $0.keyText < $1.keyText
    }
}

其他几点:

  • desription拼写错误
  • 您最好将课程符合CustomStringConvertible
  • 遵循Swift的命名惯例。你以后会感谢自己。将您的班级重命名为CellData

答案 1 :(得分:0)

像Code Different一样实施Equatable,但是对于构建“第3”集,您可能希望实际使用Set,如下所示:

let a = [1,2,3,4,5]
let b = [4,5,6,7]
let c = Set(a+b)   // {2, 4, 5, 6, 7, 3, 1}

根据需要对结果进行排序。