Guard let in swift and return

Tram Ho

The goal in this article : For beginners to step into iOS

In this article I will not focus on “guard let”, but on how to use return inside the else of the “guard let” syntax.

This is a common example of an iOS developer who has to see it every day to check if the value of the value is nil or not, and if it is nil, we’ll manage that in scope else.

So do we always have to “return” within the else clause?

Usually, newcomers often have a thought that when calling guard let , there must always be a return within the else, this is also one of the differences between it and if let

In fact, we have quite a few options besides return in this case. We can use throw (if you want to know more, link here), within else we can also use continue or break based on different cases.

Let’s walk through a few examples to understand more:

In this case, we will run the loop through an optional string and have the value in position 3 nil.

Example 1: Continue

We will see that continue will be used within else rather than return . And in this case, we will understand that it works in a way: ignore the nil value in the loop and continue browsing the next element. Yes, continue is the continuation of the loop at the next element and ignoring the current element value

Continue only partially skips rather than exits the entire loop. Now we try to call func printMyNames, we will have the output printed as:

Khatri is printed even though the value of nil is preceded because we use continue .

We also notice that the “Notice End of For Loop” line printed means that we have successfully iterated the loop without any crashes. ? So good.

Example 2: Break

Break is that you will exit the loop and not browse any later if we encounter break. In this case, the break will be called when we encounter a nil value (on the 3rd day of the loop when i = 2). The value returned will be:

Notice that Khatri did not print because the loop ended as soon as we had a break.

Example 3: Return

Here we return it please clarify what other activities than the other keywords in the loop. Return not only breaks the loop but it also exits the function immediately. Let’s see the result:

Khatri and End of For Loop have not been printed, because return it has exited the function already instead of after exiting the loop it prints more End of For Loop .

Summary

Based on the above scenarios, we can use keywords continue , break and return within the else of guard let instead of using each return. ? .


My translation here is over. Thank you for watching.

You can see the original article here: That “return” keyword in guard let statement in Swift

Share the news now

Source : Viblo