Checking if text field is empty

2019-09-11 09:14发布

问题:

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

回答1:

Try this,

if(userEmail == "" || userPassword == "" || userRepeatPassword == "") 
{
                //Do Something
}

(or)

if(userEmail == "" && userPassword == "" && userRepeatPassword == "") 
{
                //Do Something
}


回答2:

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")
}


回答3:

 if (userEmail?.isEmpty || userConfirmEmail?.isEmpty || userPassword?.isEmpty || userConfirmPassword?.isEmpty){

        alertMessage("All fields are required!");
        return;
    }

Use this method



回答4:

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.



回答5:

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



标签: swift xcode7