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("")"
A control that displays an editable text interface. iOS 13.0+ iPadOS 13.0+ macOS 10.15+ Mac Catalyst 13.0+ tvOS 13.0+ watchOS 6.0+
An object that displays an editable text area in your interface.
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.
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.
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.
You can find hundreds of similar situations in the old APIs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With