What is the difference between protection 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 the guard, I was thinking about inversion ifin another programming language.

var optString: String?
guard optString != nil else { return }
if optString == nil { return }

Does the second and third row produce the same result?

I can understand if letmaking the code easier than checking niland deploying it, but what is the purpose guard? From what I explored, I can only find people saying that he can reduce the nested if, which invert if, can do the same.

EDIT: I'm asking about inversion if NOT if let . Please read before marking it.

+4
source share
4 answers

Yes, both lines are functionally equivalent and give the same result.

guardconsidered best practice since the program should go out of scope for a reason else.

This creates an error:

guard optString != nil else { // no return statement }

But this is not so:

if optString == nil { // no return statement }

+3
source

In guardthere are two important things: inverted if(or if let) does not have:

  • guardmust have a sentence elsethat the operator must have returnor some other way to leave the protective parent area (for example, throwor break).
  • Variables declared and assigned guardare available in the parent scope guard.

guard , , if let, , , - . , .

, , guard optString != nil else { return } if optString == nil { return }, , guard :

guard if. , else, , .

: Apple.

+6

Apple:

" , .

1 return, 4 :

  • return: /
  • break:
  • continue: stop the current round and go to the next round of the cycle
  • throw: stop the current function / block and throw an error.

Your second and third lines have the same result, because it will stop your scopeteam return.

0
source

All Articles