Quick check if text is empty

I wonder how I correctly check if a uitextview is empty.

Now I have a validation function that performs validation:

if let descText = myTextView.text { if descText.isEmpty { descErrorLabel.isHidden = false } else { descErrorLabel.isHidden = true } } 

This is enough to prevent the user from sending an empty text view or I should check for spaces, for example:

 stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty 
+5
source share
1 answer

You could flip everything to something like this ...

 func validate(textView textView: UITextView) -> Bool { guard let text = textView.text, !text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else { // this will be reached if the text is nil (unlikely) // or if the text only contains white spaces // or no text at all return false } return true } 

Then you can check any UITextView as ...

 if validate(textView: textView) { // do something } else { // do something else } 
+6
source

Source: https://habr.com/ru/post/1258142/


All Articles