Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Is UITextField.text An Optional?

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("")" 
like image 303
Verticon Avatar asked Mar 17 '17 15:03

Verticon


People also ask

What is a text field on Iphone?

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+

What is UITextField?

An object that displays an editable text area in your interface.


1 Answers

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.

like image 176
Sulthan Avatar answered Sep 20 '22 18:09

Sulthan