我做了一个简单的结构并实现了 Equatable 协议(protocol):
extension MyModelStruct: Equatable {}
func ==(lhs: NModelMatch, rhs: NModelMatch) -> Bool {
let areEqual = lhs.id == rhs.id
return areEqual
}
public struct MyModelStruct {
var id : String?
var staticId : String?
init(fromDictionary dictionary: NSDictionary){
id = dictionary["id"] as? String
...
}
然后在我的项目中我得到一个 [MyModelStruct] 数组,我要做的是删除所有具有相同 id 的 MyModelStruct
let val1 = MyModelStruct(id:9, subId:1)
let val2 = MyModelStruct(id:10, subId:1)
let val3 = MyModelStruct(id:9, subId:10)
var arrayOfModel = [val1,val2,val3]; // or set but i do not know how to use a set
var arrayCleaned = cleanFunction[M2,M3]
如何制作 cleanFunction ?
有人可以帮忙吗? 谢谢大家。 Xcode:版本 7.3.1
最佳答案
我真的不希望人们只接受答案,因为这是唯一的答案,这就是为什么我要向您展示如何使用集合的力量。集合用于任何没有意义的地方,无论是否存在。集合提供了检查元素是否在集合中(contains
)、删除元素(remove
)、合并两个集合(union
)的快速方法) 还有很多。通常人们只是想要一个数组,因为他们熟悉它,但通常他们真正需要的是集合。话虽如此,以下是您如何使用集合:
struct Model : Hashable {
var id : String?
var hashValue: Int {
return id?.hashValue ?? 0
}
}
func ==(l: Model, r: Model) -> Bool {
return l.id == r.id
}
let modelSet : Set = [
Model(id: "a"),
Model(id: "hello"),
Model(id: "a"),
Model(id: "test")
]
// modelSet contains only the three unique Models
要成为集合中的类型,唯一的要求是 Hashable
协议(protocol)(它扩展了 Equatable
)。在您的情况下,您可以只返回 String
的基础 hashValue
。如果您的 id 始终是一个数字(它可能是),您应该将 id
的类型更改为 Int
,因为 String
s比 Int
效率低得多,使用 String
没有意义。
还可以考虑将此属性存储在某个地方,这样每次收到新模型时,您都可以这样做
modelSet.unionInPlace(newModels)
关于ios - 根据 Swift 中的结构属性删除数组中的重复结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38153674/