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.


I feel strongly enough about this that I'm repeating my comment on Sulthan's answer as an alternative answer.

I'm not sure Sulthan's answer really answers the question.

I can't "find hundreds of similar situations." That's because they are no longer there. They were there in Swift 1, but that was a long time ago. Since then, the APIs have been hand-tweaked to eliminate them. This one wasn't eliminated.

The whole idea of hand-tweaking the APIs was to remove unnecessary Optionals. Hundreds of values can theoretically be nil but in fact never will be, and in Swift they are therefore not Optionals. This value can never be nil; even if Objective-C code sets it to nil, it doesn't become nil. And making it nonOptional in Swift wouldn't "break" anything whatsoever. So it makes no sense that it's an Optional in Swift.

I think the right answer, therefore, is that it's a bug. During IUO removal in the course of hand-tweaking the APIs in the run-up to Swift 2.0, the label and text field text properties should have been characterized as a nonOptional String, but they weren't.