Why Is UITextField.text An Optional?

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.

Leave a Comment