比较两个文本字段的文本
如何比较两个文本字段中的文本以查看它们是否相同,例如“密码”和“确认密码”文本字段中的文本?
if (passwordField == passwordConfirmField) {
//they are equal to each other
} else {
//they are not equal to each other
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Objective-C 中,您应该使用
isEqualToString:
,就像这样:NSString
是一个指针类型。当您使用==
时,您实际上是在比较两个内存地址,而不是两个值。字段的text
属性是 2 个不同的对象,具有不同的地址。因此
==
将始终1 返回false
。在 Swift 中情况有些不同。 Swift
String
类型符合Equatable
协议。这意味着它通过实现运算符==
为您提供相等性。使以下代码可以安全使用:如果
string2
被声明为NSString
会怎样?由于 Swift 中
String
和NSString
之间完成了一些桥接,因此==
的使用仍然是安全的。1:有趣的是,如果两个
NSString
对象具有相同的值,编译器可能会在后台进行一些优化并重新使用相同的对象。因此,在某些情况下可能==
可能返回true
。显然这不是您想要依赖的东西。In Objective-C you should use
isEqualToString:
, like so:NSString
is a pointer type. When you use==
you are actually comparing two memory addresses, not two values. Thetext
properties of your fields are 2 different objects, with different addresses.So
==
will always1 returnfalse
.In Swift things are a bit different. The Swift
String
type conforms to theEquatable
protocol. Meaning it provides you with equality by implementing the operator==
. Making the following code safe to use:And what if
string2
was declared as anNSString
?The use of
==
remains safe, thanks to some bridging done betweenString
andNSString
in Swift.1: Funnily, if two
NSString
object 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 returntrue
in some cases. Obviously this not something you want to rely upon.您可以通过使用 NSString 的 isEqualToString: 方法来做到这一点,如下所示:
希望这会有所帮助!
You can do this by using the isEqualToString: method of NSString like so:
Hope this helps!