快速比较字符串可选和非可选 [英] Swift comparing Strings optionals vs non-optional

查看:72
本文介绍了快速比较字符串可选和非可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中比较字符串时,可以将非可选字符串与可选字符串进行比较.

When comparing strings in Swift, you can compare non-optional strings with optional strings.

像这样(文本是可选的,并且为空):

Like so (text is an optional, and it is empty):

UITextField.text == "" // True

是因为相等运算符本身会解包字符串吗?

Is it because the equality operator unwraps Strings by itself?

推荐答案

对于每个Equatable类型,还为可选内容定义了==操作:

For every Equatable type the == operation is also defined for optionals:

public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool

右侧的非可选项将自动升级为可选项.

The non-optional on the right side gets automatically promoted to an optional.

当两个值均为nil或两个值都不为nil并且它们相等时,可选项的==返回true.

The == for optionals returns true when both values are nil or if they are both non-nil and they are equal.

这篇关于快速比较字符串可选和非可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆