0

我正在尝试使用自定义对象创建一个 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
    }
}

谢谢你的帮助 !

4

1 回答 1

3

NSObject 是 Cocoa 类型。NSObject 的规则与 Swift 的规则不同。要使 NSObject 在集合中工作,它必须有一个与它的isEqual实现相一致的实现hash

于 2017-09-05T15:42:59.083 回答