I am attempting to check if a text field is empty but am getting an error of "Type (Bool, Bool, Bool) does not conform protocol 'Boolean Type' "
if(userEmail == "", userPassword == "", userRepeatPassword == "") {
alertMessage("All fields are required")
return
}
I am using xcode 7
Try this,
if(userEmail == "" || userPassword == "" || userRepeatPassword == "")
{
//Do Something
}
(or)
if(userEmail == "" && userPassword == "" && userRepeatPassword == "")
{
//Do Something
}
Your should have used &&
as this:
let userEmail = "William"
let userPassword = "Totti"
let userRepeatPassword = "Italy"
if(userEmail == "" && userPassword == "" && userRepeatPassword == "") {
print("okay")
}
However, there is another way to do it and it is:
if(userEmail.isEmpty && userPassword.isEmpty && userRepeatPassword.isEmpty){
print("okay")
}
Also another way is to check the number of characters like this:
if(userEmail.characters.count == 0 && userPassword.characters.count == 0 && userRepeatPassword.characters.count == 0){
print("okay")
}
if (userEmail?.isEmpty || userConfirmEmail?.isEmpty || userPassword?.isEmpty || userConfirmPassword?.isEmpty){
alertMessage("All fields are required!");
return;
}
Use this method
This is the simplest way to check if a textfield is empty or not:
For Example:
if let userEmail = UserEmail.text, !userEmail.isEmpty,
let userPassword = UserPassword.text, !userPassword.isEmpty,
let userRepeatPassword = UserRepeatPassword.text, !userRepeatPassword.isEmpty { ... }
If all conditions are true then all variables are unwrapped.
After Swift 3.0, better to use the early binding statements, to make the code more clear.
guard !(userEmail.isEmpty)! && !(userPassword.isEmpty)! && !(userRepeatPassword.isEmpty)! else {
return
}
// Do something if the fields contain text