Custom equality in swift objects preserving compatibility with legacy Objective-C code

Yes, you need to override isEqual (and hash) to make your objects fully Objective-C compatible. Here's a Playground-ready example for the syntax:

import Foundation

class MyClass: NSObject {

    var value = 5

    override func isEqual(object: AnyObject?) -> Bool {
        if let object = object as? MyClass {
            return value == object.value
        } else {
            return false
        }
    }

    override var hash: Int {
        return value.hashValue
    }
}

var x = MyClass()
var y = MyClass()
var set = NSMutableSet()

x.value = 10
y.value = 10
set.addObject(x)

x.isEqual(y) // true
set.containsObject(y) // true

(syntax current as of Xcode 6.3)


You could also implement a custom equatable, for instance:

func == (lhs: CustomClass, rhs: CustomClass) -> Bool {
     return lhs.variable == rhs.variable
}

This will allow you to simply check equality like this:

let c1: CustomClass = CustomClass(5)
let c2: CustomClass = CustomClass(5)

if c1 == c2 { 
    // do whatever
}

Be sure your custom equatable is outside the class scope!


swift3 sig:

open override func isEqual(_ object: Any?) -> Bool {
    guard let site = object as? PZSite else {
        return false
    }
....
}

Tags:

Equality

Swift