How do you compare the text in two text fields to see if they are the same, such as in “Password” and “Confirm Password” text fields?
if (passwordField == passwordConfirmField) {
//they are equal to each other
} else {
//they are not equal to each other
}
In Objective-C you should use
isEqualToString:, like so:NSStringis a pointer type. When you use==you are actually comparing two memory addresses, not two values. Thetextproperties of your fields are 2 different objects, with different addresses.So
==will always1 returnfalse.In Swift things are a bit different. The Swift
Stringtype conforms to theEquatableprotocol. Meaning it provides you with equality by implementing the operator==. Making the following code safe to use:And what if
string2was declared as anNSString?The use of
==remains safe, thanks to some bridging done betweenStringandNSStringin Swift.1: Funnily, if two
NSStringobject have the same value, the compiler may do some optimization under the hood and re-use the same object. So it is possible that==could returntruein some cases. Obviously this not something you want to rely upon.