if fooOK
if barOK {
if bazOK {
// do something
}
}
}
can be written as: guard fooOK else { return }
guard barOK else { return }
guard bazOK else { return }
// 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). return unless fooOK;
return unless barOK;
return unless bazOK;
# do somethingUsing "if" or "unless", whichever is more appropriate, is far more readable than "guard".
Moreover, there are many languages where an assignment or an initialization can appear in any place where an expression can appear. Such general rules are always better than special rules like allowing new bindings in a "guard", but not in an "if". Pattern matching does not need any special syntax, it should work in the standard alternative program structure of that programming language, regardless whether it is called "select", "case" or "switch".
It always annoys me when the creators of new programming languages demonstrate amateurism, by inventing new worse alternatives than those that existed in various older programming language, already many decades ago.
There are plenty of new programming languages that claim to be better than C, which may be true, but they fail to match programming languages much older than C.
How is a different (and longer) keyword "far more readable"? That's just a matter of preference and familiarity. The reason for choosing a different keyword is that it's not quite equivalent to an unless as the {} block must exit the surrounding scope. You read it like an assert statement with a custom handler.
> Moreover, there are many languages where an assignment or an initialization can appear in any place where an expression can appear. Such general rules are always better than special rules like allowing new bindings in a "guard", but not in an "if".
You can introduce bindings in an if too. The special thing about guard is that you can introduce a binding which is valid for the remainder of the scope outside the {} block (where the condition is true) but not inside (where the condition is false).