The current style guide is clear regarding using guard
instead of nesting if
, but it could show an example when if
should be used instead of guard
, aka where there is no unwrapping of optionals needed:
if !success { return false }
guard success else { return false }
Best described here: https://www.natashatherobot.com/swift-when-to-use-guard-vs-if/
I would almost say that the Failing Guards section covers this:
Guard statements are required to exit in some way.
...or as Natasha's blog put it:
think of guard as a lightweight Assert
You should therefore do:
guard success else { return false }
The benefit of the guard
here is that the compiler will guarantee the exit. Example:
// This compiles fine and a bug risks going unnoticed
if !success {
// Some code here
// Forgot the return statement
}
// Compiler error, you are required to return and the bug is prevented
guard success else {
// Some code here
// Forgot the return statement
}
@RobertGummesson so your rule of thumb would be that - even if you don't need to unwrap optionals - you'd use guard
over if
if you encounter failure that requires exiting. Correct?
@agirault - Yes, either that or you simply require exiting (whether or not it's due to a failure).
Most helpful comment
I would almost say that the Failing Guards section covers this:
Guard statements are required to exit in some way.
...or as Natasha's blog put it:
think of guard as a lightweight Assert
You should therefore do:
The benefit of the
guard
here is that the compiler will guarantee the exit. Example: