我正在尝试使用自定义对象创建一个Set。 这是有效的,如果我使用一组自定义对象,则没有重复项:
public class AttributesGroup: Hashable, Equatable, Comparable {
open var id: Int!
open var name: String!
open var position: Int!
public init (id: Int = 0, name: String = "", position: Int = 0) {
self.id = id
self.name = name
self.position = position
}
open var hashValue: Int {
get {
return id.hashValue
}
}
public static func ==(lhs: AttributesGroup, rhs: AttributesGroup) -> Bool {
return lhs.id == rhs.id
}
public static func < (lhs: AttributesGroup, rhs:AttributesGroup) -> Bool {
return lhs.position < rhs.position
}
}
我用NSObject扩展我的类,因为NSObject已经实现了Hashable协议(以及Equatable)我必须覆盖hashValue,这不再适用了,如果我使用一组自定义对象有重复,我该怎么做这里做错了? :
public class AttributesGroup: NSObject, Comparable {
open var id: Int!
open var name: String!
open var position: Int!
public init (id: Int = 0, name: String = "", position: Int = 0) {
self.id = id
self.name = name
self.position = position
}
open override var hashValue: Int {
get {
return id.hashValue
}
}
public static func ==(lhs: AttributesGroup, rhs: AttributesGroup) -> Bool {
return lhs.id == rhs.id
}
public static func < (lhs: AttributesGroup, rhs:AttributesGroup) -> Bool {
return lhs.position < rhs.position
}
}
感谢您的帮助!
答案 0 :(得分:3)
NSObject是一个Cocoa类型。 NSObject的规则与Swift的规则不同。要使NSObject在集合中工作,它必须具有与isEqual
的实现一致的hash
实现。