UITextPosition's equality test: `==` seems to work, but I'm not sure if it's correct to use `==`

I need to test for equal two UITextPosition's. I use == and appears to work:

position1 == position2

Does this really work? If so, why does it work comparing two class instances?

I am not sure about this. Just to be safe, I end up using UITextInput.compare(_:to:)

NSObject conforms to Equatable by having == call isEqual(_:). Unfortunately, that's as much as is documented here; if UITextPosition overrides isEqual(_:) (which it does not have to declare in Objective-C), then == will work, and if it does not then it will not.

I would suggest filing a documentation bug with Apple to make this clear.

(For that matter, NSObject's == should also have documentation saying it will call isEqual(_:).)

FB9093618 for both NSObject == and UITextPosition.isEqual


1 Like

So according to UIImage doc, == may not always work:

let image1 = UIImage(named: "MyImage")
let image2 = UIImage(named: "MyImage") 
if image1 != nil && image1!.isEqual(image2) {
    // Correct. This technique compares the image data correctly.
if image1 == image2 {
    // Incorrect! Direct object comparisons may not work.

So whether == works for so UIxxx objects equality test is really depends, and there is no convention?

Terms of Service

Privacy Policy

Cookie Policy