guard is an inverted if statement, with the additional requirement that the branch must exit the parent scope. It's useful sometimes for readability, particularly for avoiding the "pyramid of doom" when you have a lot of preconditions that need to be checked:
if fooOK
if barOK {
if bazOK {
// do something
}
}
}
Obviously there are other options (like writing a negated if), but sometimes guard is more readable. It's a style thing.
The more important use case for guard is that 'guard let' statements can pattern-match and introduce bindings that are valid for the rest of the scope:
guard let foo = someOptional else { return }
print(foo);
This is useful enough that Rust copied it in the form of 'let ... else {}' statements (but did not bring over boolean guard statements).
guard has two advantages: the compiler ensures that you exit the current scope if the condition does not hold (via return, break, continue, etc), and bindings established in the guard clause (e.g. let foo = optionalBar) remaining in scope after the guard block, rather than inside it like an if block.
The more important use case for guard is that 'guard let' statements can pattern-match and introduce bindings that are valid for the rest of the scope:
This is useful enough that Rust copied it in the form of 'let ... else {}' statements (but did not bring over boolean guard statements).