Obviously, you should eliminate that != nil
.
I’d also recommend:
- trimming whitespace so someone doesn’t enter space to get past the validation;
- use
isEmpty
of the trimmed string to make sure there’s something there;
- start properties and method names with lowercase letters;
- I personally give my
UITextField
properties a TextField
suffix (so I can distinguish the emailTextField
text field from the email
string.
Thus, perhaps something like:
@IBAction func didTapSignup(_ sender: Any) {
guard let email = emailTextField.text?.trimmingCharacters(in: .whitespaces),
!email.isEmpty,
let password = passwordTextField.text?.trimmingCharacters(in: .whitespaces),
!password.isEmpty else {
// tell the user that validation failed here ...
// ... and then return
return
}
// do something with `email` and `password`
}
You might want to check, for example, that the email and password pass some rudimentary rules:
let emailRegexString = "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$" // oversimplified email regex
func isAcceptable(email: String, password: String) -> Bool {
let isEmailAcceptable = email.range(of: emailRegexString, options: .regularExpression) != nil
let isPasswordAcceptable = password.count > 4
return isEmailAcceptable && isPasswordAcceptable
}
And then
@IBAction func didTapSignup(_ sender: Any) {
guard let email = emailTextField.text?.trimmingCharacters(in: .whitespaces),
let password = passwordTextField.text?.trimmingCharacters(in: .whitespaces),
isAcceptable(email: email, password: password) else {
// tell the user that validation failed here ...
// ... and then return
return
}
// do something with `email` and `password`
}
Note, that regex is a grossly over-simplified email validation. But you can go nuts on the regex if you really want.
I’d also, at a bare minimum, set up my email and password text fields so that spaces are not allowed. So, specify the delegate
for the email and password text fields and then prohibit spaces:
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return string.rangeOfCharacter(from: .whitespacesAndNewlines) == nil
}
}