Guard, Something Different Than If

Forms. Validations. Forms and validations everywhere with Guard.

Let’s say we have registration form which 4 inputs fields: name, passwords, and email. How checking code could look like?

if validate(login: login.text) {
    
if validate(pass: pass.text, passConfirm: passConfirm.text) {
       
if validate (email: email.text) {
       
    // sucess
       }
else {
           
// email is incorrect
       }
   }
else {
       // passwords are incorrect
   }
}
else {
    // login is incorrect
}

It works… but, it isn’t the most beautiful code and it’s easy to get confused with curly braces to close them correctly especially when we will need to add something between them. How many of you closed curly brace incorrectly and spent an hour to find why the code doesn’t work?

Swift has something like GUARD. When the condition inside is false then it finishes function with return (or can throw, for example, Custom Error). This will break embedded ifs to separate one.

guard validate(login: login.text) else {
    // login is incorrect
    
return
}
guard validate(pass: pass.text, passConfirm: passConfirm.text) else {
 
   // passwords are incorrect
    
return
}
guard validate(email: email.text) else {
  
  // email is incorrect
    
return
}
// sucess

Now, it looks prettier and easier to modify than earlier, doesn’t it?