Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 445
Joshua Avatar asked Jan 05 '23 20:01

Joshua


2 Answers

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).
  • Variables declared and assigned by 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 an if statement. It lets you write the code that’s typically executed without wrapping it in an else block, and it lets you keep the code that handles a violated requirement next to the requirement.

Source: Apple's documentation.

like image 138
0x416e746f6e Avatar answered Jan 15 '23 00:01

0x416e746f6e


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 }

like image 30
Code Avatar answered Jan 15 '23 00:01

Code