[英]Swift comparing Strings optionals vs non-optional
When comparing strings in Swift, you can compare non-optional strings with optional strings. 在比较Swift中的字符串时,可以将非可选字符串与可选字符串进行比较。
Like so (text is an optional, and it is empty): 像这样(文本是可选的,它是空的):
UITextField.text == "" // True
Is it because the equality operator unwraps Strings by itself? 是因为平等运算符单独解开字符串吗?
For every Equatable
type the ==
operation is also defined for optionals: 对于每个
Equatable
类型,也为optionals定义了==
操作:
public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool
The non-optional on the right side gets automatically promoted to an optional. 右侧的非可选项会自动升级为可选项。
The ==
for optionals returns true
when both values are nil
or if they are both non-nil and they are equal. 当两个值都
nil
或者它们都是非零并且它们相等时, ==
for optionals返回true
。
Your theory doesn't hold in the following example: 您的理论不适用于以下示例:
let x: String? = nil
if x == "" {
print("True")
} else {
print("False") //Printed
}
What's actually happening here is that the text
property is never actually nil
upon initialisation — it is instead an empty string, as given by the documentation : 这里实际发生的是
text
属性在初始化时实际上从未实际nil
- 它是一个空字符串,如文档所示 :
This string is @"" by default.
默认情况下,此字符串为@“”。
The Swift compiler does not implicitly unwrap any optionals, it instead leaves that responsibility to the programmer. Swift编译器不会隐式解包任何选项,而是将该责任留给程序员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.