Sorry, if this is a noob question because I am new to Swift and cannot find this answer from Google.
When I first saw guard, I think of invert if
in other programming language.
var optString: String?
guard optString != nil else { return }
if optString == nil { return }
Doesn't the second and third line produce the same result?
I can understand if let
make the code simpler than checking nil
and unwrapping it but what is the purpose of guard
? From what I researched, I can only find people saying that it can reduced nested if
which invert if
can do the same.
EDIT: I am asking about invert
if
NOTif let
. Please read the question before flagging it.
There are 2 important things about guard
that inverted if
(or if let
for that matter) does not have:
guard
must have else
clause that must have return
statement or some other way of leaving the guard's parent scope (e.g. throw
or break
).guard
are available in the guard
's parent scope.The whole point of guard
is that it allows you to avoid cumbersome constructs like if let
body continuing to the end of the method because the code must only execute if some unwrapping of the optional is successful. Basically, it's a cleaner way to implement the early exit.
So, to answer your direct question, yes guard optString != nil else { return }
is equivalent to if optString == nil { return }
, but that's not what guard
was introduced for:
Using a
guard
statement for requirements improves the readability of your code, compared to doing the same check with anif
statement. It lets you write the code that’s typically executed without wrapping it in anelse
block, and it lets you keep the code that handles a violated requirement next to the requirement.
Source: Apple's documentation.
Yes, both lines are functionally equivalent and produce the same result.
guard
is considered better practice since the program must exit the scope in its else
cause.
This generates an error:
guard optString != nil else { // no return statement }
But this does not:
if optString == nil { // no return statement }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With