The other day I witnessed the difference between nil and "" (from the letter), so I will record it.
UITextField (textField
) for entering a message and a button (sendButton
) for sending it
Was implemented.
Here, it is meaningless if the textField does not have a value, so I thought about setting the submit button so that it can be used only when the textField has a value. The implementation is as follows
@objc func textFieldDidChange(sender: UITextField) {
if textField.text == nil {//Pay attention to this line
sendButton.isEnabled = false
} else {
sendButton.isEnabled = true
}
}
textFieldDidChange ()
is a method that is called every time the value of textField
changes.
Let's check the execution result.
Of course, you can't press the submit button because there is no value in textField
.
Characters are entered and the send button can be pressed.
The send button can be pressed even though there are no characters.
: frowning2: Nande? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? : frowning2:
From the above events, it was found that ** if you enter a character once and then delete it, it is not nil **.
I changed the conditional expression thinking "Why was it written as textField.text == nil
in the first place? "
@objc func textFieldDidChange(sender: UITextField) {
if commentTextField.text == ""{//Pay attention to this line
sendButton.isEnabled = false
} else {
sendButton.isEnabled = true
}
}
This time, I changed "" (from the character) to nil in the conditional expression and put it in. Check the execution result.
It is difficult to convey with the image alone, but we were able to confirm normal operation.
Regarding UITextField, the handling of conditional expressions and elements corresponds as follows.
== nil | == "" | |
---|---|---|
initial state | true | true |
Enter characters | false | false |
Delete the entered characters | false | true |
This event gave me a little better understanding of the difference between nil and "". Until now, I was often told in books that "nil and" "are different !!", and I remembered myself, but this was the first time I had witnessed it in implementation.
nil Completely innocent with no value in it! Insanely pure! !! Natural water Super beautiful
An image that looks like "a state without any value" and artificially reproduces "a state without a value" Feeling that sewage is filtered and brought to nature A little dirty
If you have any problems with this recognition, I will write an article again.
Recommended Posts