Is this the right way to check if a field is blank?

This is inside the function, so any textField passed as an argument can respond to the method checkForEmptyFields:

textField.addTarget(self, action: #selector(checkForEmptyFields(sender:)), 
for: UIControlEvents.editingChanged)

This is the method checkForEmptyFields:

 func checkForEmptyFields(sender:UITextField){

        self.loginButton.isEnabled = (sender.text?.trim().isEmpty)! == false

    }

This is a simple String extension for cropping control:

extension String
{
    func trim() -> String
    {
        return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
    }
}

Everything seems to be working fine, but I would like to know if this is correct, and if I forgot something important (or I made some mistake). Thank!

+4
source share
2 answers

It might be safer to also ensure that the text is not null.

func checkForEmptyFields(sender: UITextField) {
    let isTextEmpty = sender.text?.trim().isEmpty ?? true
    self.loginButton.isEnabled = !isTextEmpty
}

Your overall approach seems fine, though.


As @matt explained in the comments, you can encapsulate some of this behavior in an extension to UITextField.

extension UITextField {
    var isEmpty: Bool {
        return self.text?.trim().isEmpty ?? true
    }
}

Your function can be simplified:

func checkForEmptyFields(sender: UITextField) {
    self.loginButton.isEnabled = !sender.isEmpty
}

: "" trimmed(), String. Swift API Design Guidelines.

+2

, . !

, , , ...

func checkForEmptyFields(sender: UITextField) {
    if let trimmedText = sender.text?.trim(), !trimmedText.isEmpty {
        loginButton.isEnabled = true
    } else {
        loginButton.isEnabled = false
    }
}

, , - ( ?? true ?? false?)

+1

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


All Articles