问题描述
它开始时是一个空字符串,而不是nil.即使将其显式设置为nil,它仍然是一个空字符串.我不明白也许通过分配nil使其易于清除?用它编写代码很笨拙.
It starts out as an empty string instead of nil. Even when it is explicitly set to nil it remains an empty string. I don't get it. Perhaps to make it easy to clear by assigning nil? Writing code with it is clunky.
var textField = UITextField()
print(textField.text) // prints "Optional("")"
textField.text = nil
print(textField.text) // prints "Optional("")"
推荐答案
这是历史. UITextField
在空字符串和nil
字符串之间没有任何区别.在Objective-C中,无需区别它们,因为您可以在Objective-C中的nil
上调用方法.
This is a historical thing. UITextField
does not make any difference between an empty string and a nil
string. In Objective-C there was no need to make a difference between them because you can call methods on nil
in Objective-C.
此外,Objective-C也无法阻止用户将nil
分配给属性.结果合同是text
可以是可选的.在Objective-C中没什么区别.
Also, there was no way in Objective-C to prevent users from assigning nil
to a property.The resulting contract is that text
can be optional. In Objective-C that makes no difference.
在Swift中,我们无能为力,因为UITextField.text
合同必须更改,可能会破坏许多已经编写的代码.请注意,即使从未从该方法返回nil
,您仍然可以分配nil
来重置该值.
In Swift there is not much we can do because UITextField.text
contract would have to change, possibly breaking lots of already written code. Note that even if nil
is never returned from the method, you can still assign nil
to reset the value.
您可以在旧的API中找到数百种类似的情况.
You can find hundreds of similar situations in the old APIs.
这篇关于为什么UITextField.text是可选的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!