Defer. Wait…. OK

-How are you?
-…
-Why don’t you answer?
-I’m waiting until you finish

Sometimes a function may finish earlier because data is incorrect or some condition is not meet. What if we’d like to do some code at the end of that function. Swift has a solution for that. It’s Defer.

The code inside Defer will be executed finally. Let’s take an example of validating form Guard Example.

Three checks if the user registration form is correct.

guard validate(login: “Some invalid login”) else {
   
 // login is incorrect
    
print(“Login is invalid”)
    
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

Besides the result, we’d like to remove text from password input. Yet we don’t know which is incorrect and we don’t try put clearing code inside else part.

Using defer at the beginning of the method we are sure it’ll be executed at the end of validation.

defer {
    pass.text = “”
    passConfirm.text = “”
    print(“Password has been cleared”)
}
guard validate(login: “Some invalid login”) else {
     // login is incorrect
    print(“Login is invalid”)
    return
}
// The rest of code…

OUTPUT

Login is invalid
Password has been cleared

Log with password is after log with invalid login.