Joshua Joshua - 5 months ago 14
Swift Question

What is the different between guard and invert if

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
NOT
if let
. Please read the
question before flagging it.

Answer

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 }

Comments