I have two UITextField
instances and upon update I need to figure out which one is updated, usually I’d use ===
to check reference identity, but accidentally put ==
instead and it worked. So I wonder if UITextField
conforms to Equatable
and what actually are involved in comparison?
To illustrate:
let textFieldA = UITextField()
let textFieldB = UITextField()
textFieldA.text = "A"
textFieldB.text = "B"
print("A.text", textFieldA.text)
print("B.text", textFieldB.text)
print("A == A:", textFieldA == textFieldA)
print("A == B:", textFieldA == textFieldB)
print("A === B:", textFieldA === textFieldB)
textFieldB.text = "A"
print("A.text", textFieldA.text)
print("B.text", textFieldB.text)
print("A == A:", textFieldA == textFieldA)
print("A == B:", textFieldA == textFieldB)
print("A === B:", textFieldA === textFieldB)
Output:
A.text Optional("A")
B.text Optional("B")
A == A: true
A == B: false
A === B: false
A.text Optional("A")
B.text Optional("A")
A == A: true
A == B: false
A === B: false
So ==
and ===
works the same regardless of whether their text are same or different, I wonder what is happening under the hood?
Thanks!
2
Answers
UITextField
extendsUIControl
->UIView
->UIResponder
->NSObject
which conforms to theNSObject
protocol.NSObject
conforms toHashable
which extendsEquatable
.Ultimately the Swift
==
operator is going to call theisEqual:
method thatUITextField
inherits fromNSObject
. The default implementation of this is to simply compare the pointer.UITextField
does not overrideisEqual:
to compare thetext
property or any other property. So the end result is that==
and===
are effectively the same in this case.Use
===
when you only care about if the two references are to the same object. Don’t use==
just because it gives the same result in this case. It’s possible that could change in some future update.UITextField
is a subclass ofNSObject
, andNSObject
conforms toHashable
, which means it also conforms toEquatable
.NSObject.==
is implemented by delegating toisEqual
, and the default implementation ofisEqual
compares object identities. See the code in NSObject.swift in the swift-corelibs-foundation implementation,And frankly, that is the only reasonable implementation of
NSObject.==
I can think of.Evidently,
UITextField
did not overrideisEqual
, and so comparing with==
produces the same result as comparing with===
.