0

I get an error saying 'characters' is unavailable: Please use String directly.


extension LoginViewController : UITextFieldDelegate {

    func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {

        if let username = self.usernameField.text,
            let password = self.passwordField.text {

            if ((username.characters.count > 0) && //This is where I get the error
                (password.characters.count > 0)) { //This is where I get the error
                self.loginButton.isEnabled = true
            }
        }

        return true
    }

}

How can I fix this?

GBMR
  • 594
  • 1
  • 7
  • 16

3 Answers3

2

Simply remove .characters

extension LoginViewController : UITextFieldDelegate {

    func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {

        if let username = self.usernameField.text,
            let password = self.passwordField.text {

            if username.count > 0 &&
                password.count > 0 {
                self.loginButton.isEnabled = true
            }
        }

        return true
    }

}
Neulio
  • 312
  • 2
  • 9
2

you don't need to state characters to count since it will already be counted when you type username.count or password.count

if ((username.count > 0) && (password.count > 0)) {

galvatron
  • 21
  • 3
2

In Swift never check for empty string or empty collection type with .count > 0, there is the dedicated method isEmpty.

And in Swift parentheses around if expressions are not needed and the && operator can be replaced with a comma

if !self.usernameField.text!.isEmpty, !self.passwordField.text!.isEmpty {
    self.loginButton.isEnabled = true
}

The text property of UITextField is never nil so force unwrapping is fine.

vadian
  • 274,689
  • 30
  • 353
  • 361