我有以下基于节点/键组合的类:
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")]
我需要一个函数,该函数将返回第三组类“ cellData”,但仅具有同一节点/键组合的唯一实例。这意味着我的最终设定必须如下所示:
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。先感谢您!
最佳答案
首先,使您的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
关于arrays - 查找和删除自定义数组类型中的重复项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40642069/