swiftpfobject

Swift indexOf, == operator override not getting called


I am getting frustrated with how Swift handles equality. Or I'm just missing something. How come these 2 indexOf DOESN'T work the same way?

let first = self.objects.indexOf(object) //This returns nil
let second = self.objects.indexOf{$0 == object} //This returns the index

My == override:

func ==(lhs: MyObject, rhs: MyObject) -> Bool {
    return lhs.someProperty == rhs.someProperty
}

The == override doesn't get called in the first indexOf. Why is that so? This feels really dangerous.

(MyObject is a subclass of PFObject (Parse.com objects). I don't know if this is what's messing this up.)


Solution

  • Since your Object is subclass of PFObject, and PFObject is subclass of NSObject, and NSObject already confirm to Equatable by using the isEqual method to implement. So your == operator override is not working. You should override the isEqual method. (To be honest, it's horrible :(

    sample code:

    class Object: NSObject {
        var value: Int
        init(value: Int) {
            self.value = value
        }
    
        override func isEqual(object: AnyObject?) -> Bool {
            guard let obj = object as? Object else { return false }
            return self.value == obj.value
        }
    }
    
    // If your class is not inherit from any ObjC class:
    //extension Object: Equatable {}
    //func ==(lhs: Object, rhs: Object) -> Bool {
    //    return lhs.value == rhs.value
    //}
    
    let c = Object(value: 3)
    let objs = [Object(value: 1), Object(value: 2), Object(value: 3)]
    
    let index = objs.indexOf(c)
    let index2 = objs.indexOf { $0 == c }
    print(index) // Optional(2)
    print(index2) // Optional(2)