Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

ios - 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("")"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...