Let's say I'm implementing a root class in Swift, which I declare adopts the Equatable
protocol (I want to be able to tell if an array of my type contains a given instance or not).
What is the difference -if any, in this specific case- between implementing the protocol's required ==
operator as:
public static func ==(lhs: MyClass, rhs: MyClass) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
...as opposed to just doing this:
public static func ==(lhs: MyClass, rhs: MyClass) -> Bool {
return (lhs === rhs)
}
As a reference, this is what the documentation says about ObjectIdentifier()
:
A unique identifier for a class instance or metatype. In Swift, only class instances and metatypes have unique identities. There is no notion of identity for structs, enums, functions, or tuples.
...and this is what the "Basic Operators" section of The Swift Programming Language (Swift 3) says about the ===
operator:
NOTE
Swift also provides two identity operators (
===
and!==
), which you use to test whether two object references both refer to the same object instance. For more information, see Classes and Structures.