Swift | Set with NSObject

805 views Asked by At

I'm trying to create a Set with custom objects. This is working, If I use a Set of my custom objects there is no duplicates :

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
    }
}

I extend my class with NSObject, since NSObject already implements Hashable protocol (and also Equatable) I have to override hashValue, and this is not working anymore, If I use a Set of my custom objects there is duplicates, what do I do wrong here ? :

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
    }
}

Thanks for your help !

1

There are 1 answers

1
matt On BEST ANSWER

NSObject is a Cocoa type. The rules for NSObject are different from the rules for Swift. To make an NSObject work in a set, it must have an implementation of isEqual consonant with its implementation of hash.