kings09045 kings09045 - 3 months ago 8
Swift Question

Swift optimize if else condition

I have a function with a long if else condition to check whether all the details are valid or not. However, I would like to optimize the if-else condition.

if emailInput!.isEmailValid && passwordInput!.isPasswordValid && usernameInput!.isUserNameValid && testConfirmedPwd == true && photoPick != "image1"{

print("valid")
}
else{

print("not valid")

}


Because I would like to know which part of the condition is not valid and
print
it out instead of doing it all together. For example, If
emailInput
is invalid when others are valid.

Answer

To know which part of the condition fails, you can check each case individually and react accordingly:

if !emailInput!.isEmailValid {
    // Invalid email
} else if !passwordInput!.isPasswordValid {
    // Invalid pwd
} else if !usernameInput!.isUserNameValid {
    // Invalid username
} else if !testConfirmedPwd {
    // Invalid pwd
} else if photoPick == "image1" {
    // Invalid image
}else{
    print("valid")
}
Comments