user1094081
user1094081

Reputation:

Is this the right way to test if a field has been left empty?

This is inside a function, so that any textField passed as 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 extension of String for manage the trimming:

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

Anything seems to work just fine but I'd like to know if this is the right way to proceed and if I forgot something important (or I made any mistake). Thanks!

Upvotes: 4

Views: 36

Answers (2)

Ashley Mills
Ashley Mills

Reputation: 53111

Per my comment above, don't force unwrap. Really!

I'd probably handle it like…

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

It's more verbose, but I think this clearly states your intent - nil coalescing can sometimes be confusing to read and debug (should it be ?? true or ?? false?)

Upvotes: 1

nathangitter
nathangitter

Reputation: 9777

It would probably be safer to also ensure that the text is not nil.

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

Your overall approach seems fine though.


As @matt has suggested in the comments, it's possible to encapsulate some of this behavior into an extension on UITextField.

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

Your function could be simplified to this:

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

A side note: The "Swiftier" name for your extension is trimmed(), as it is returning a new String instance. This adheres to the Swift API Design Guidelines.

Upvotes: 2

Related Questions