kings09045 kings09045 - 1 year ago 92
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("not valid")


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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download