-1

I'm trying to identify which UITextField is being passed into the delegate function textFieldDidEndEditing(_:UITextField). I'm doing a comparison operation, but I'm not sure whether to use ==, isEqual(), or something else entirely.

I want to stress that I am comparing the UITextFields themselves to see if they are the same and not their text.

Here's the code as I have it now:

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField == titleTextField {
        self.poll?.titleText = textField.text ?? ""
    }
    else {
        self.poll?.allOptions[textField.tag].text = textField.text ?? ""
    }
}
s_khillon
  • 81
  • 3
  • 7

1 Answers1

1

According to this response, == checks if two pointers point to the same place, and are therefore the same object. isEqual() compares the values of the two objects.

You're looking to see if the UITextField passed into the function points to the same location in memory as your variable declaration of titleTextField, so you want to use ==.

EDIT: Martin pointed out that == in Swift is not the same thing as == in Objective C (that would be === in Swift) and that it makes no difference which one you use. Thank you!

Community
  • 1
  • 1
s_khillon
  • 81
  • 3
  • 7
  • 1
    Your linked answer refers to Objective-C. `==` in Swift and `==` in Objective-C are *not* the same thing. – Martin R Sep 12 '16 at 10:57
  • But (unless you override `isEqual` for the UITextField class) it actually makes no difference what you use. The default implementation of `==` for `NSObject` subclasses calls `isEqual:`, compare for example http://stackoverflow.com/questions/33319959/nsobject-subclass-in-swift-hash-vs-hashvalue-isequal-vs. `==` in Objective-C corresponds to `===` in Swift. – Martin R Sep 12 '16 at 11:02