0

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 !

Aximem
  • 714
  • 8
  • 27
  • As always, **never ever** declare properties as implicit unwrapped optionals which are initialized in an `init` method with non-optional values. Unfortunately many *horrible* tutorials suggest this *horrible* habit. Don't do that, never. Remove the exclamation marks. – vadian Sep 05 '17 at 16:10
  • Compare point #2 of https://stackoverflow.com/a/42286148/2976878 as well as https://stackoverflow.com/q/33319959/2976878 – Hamish Sep 05 '17 at 16:13
  • @vadian You're totally right, this is a bad habit. Thanks. – Aximem Sep 05 '17 at 17:30
  • @Hamish Very interesting, I get it now thanks – Aximem Sep 05 '17 at 17:30

1 Answers1

3

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141