Joshua Joshua - 1 year ago 56
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

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
and unwrapping it but what is the purpose of
? From what I researched, I can only find people saying that it can reduced nested
which invert
can do the same.

EDIT: I am asking about invert
if let
. Please read the
question before flagging it.

Answer Source

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 }