0

I'm trying to figure out when I should use === to compare UIViews. I realized I've been using == without really thinking about how UIView is a reference type. But it's never caused me any problems, so it appears that === is never needed for UIViews?

My understanding of value compare ==, and identity compare ===, based on this previous question is that for classes you need to use === to know if you have the same instance, and == to know if they have the same value. However for the UIView class, == seems to work exactly like the === operator.

let v1 = UIView()
let v2 = UIView()
XCTAssertTrue(v1 === v1)
XCTAssertTrue(v1 == v1)
XCTAssertTrue(v1.isEqual(v1))

XCTAssertFalse(v1 === v2)
XCTAssertTrue(v1 == v2)
XCTAssertTrue(v1.isEqual(v2))

Based on that understanding I expect these all to pass. To know if v1 and v2 are different instances I should use ===, and == should be true since they have the same property values. However that is not what happened.

failed tests

The == and === were both false. Shouldn't these work differently? These views have the same property values.

Does UIView use === to implement Equatable? Is there no reason to ever use === on UIViews?

user2129800
  • 131
  • 1
  • 9
  • "Does UIView use === to implement Equatable" I don't know for sure, but that seems pretty reasonable. I can't really imagine how else you'd define equality of two views. – Alexander May 01 '20 at 18:59

2 Answers2

4

It's because by default == for Objective-C objects is ===. For it to be otherwise (e.g. property-by-property comparison), you'd need to override isEqual:, but generally Cocoa classes do not. (Foundation classes such as NSString obviously do; what matters it the characters of the string, not where it is stored.)

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • So generally for any NSObject subclass, I would not need to ever use ===, unless I know it overrides isEqual in some way? I guess that makes sense. – user2129800 May 01 '20 at 20:53
  • 3
    The way it works in Swift is that Swift `==` defaults to `isEqual`; but in Objective-C / Cocoa, `isEqual` defaults to object equality, which is what `===` is. But _you_ should not rely on trickery; the way to write code is to _say what you mean_. If you mean "are equal", use `==`. If you mean "are identically the same object", use `===`. – matt May 01 '20 at 21:21
0

It's unlikely that two different UIView instances will have all the properties and attributes the same.

When you compare two different individual instances UIView's(having different values) using == will always return false unless you conform to Equatable protocol and provide a custom equality criteria.

Also, === returns false since their references have different heap locations.

Vikram Parimi
  • 777
  • 6
  • 29