Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit GUARD outside and inside a function - Swift [duplicate]

Tags:

swift

guard

In the following code I am practicing the use of GUARD (Book: OReilly Learning Swift)

guard 2+2 == 4 else {
print("The universe makes no sense")
return // this is mandatory!
}
print("We can continue with our daily lives")

Why do I get the following code error?

error: return invalid outside of a func

Or is GUARD only used within functions?

like image 980
Mario Burga Avatar asked Dec 04 '17 17:12

Mario Burga


People also ask

How do you exit a closure in Swift?

A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter's type to indicate that the closure is allowed to escape.

How do you write a guard let statement in Swift?

The syntax of the guard statement is: guard expression else { // statements // control statement: return, break, continue or throw. } Note: We must use return , break , continue or throw to exit from the guard scope.

What does guard keyword do in Swift?

Swift's guard keyword lets us check an optional exists and exit the current scope if it doesn't, which makes it perfect for early returns in methods.

What is guard statement?

Regardless of which programming language is used, a guard clause, guard code, or guard statement, is a check of integrity preconditions used to avoid errors during execution. A typical example is checking that a reference about to be processed is not null, which avoids null-pointer failures.


1 Answers

If the condition in your guard statement is not met, the else branch has to exit the current scope. return can only be used inside functions, as the error message shows, but return is not the only way to exit scope.

You can use throw outside functions as well and if the guard statement is in a loop, you can also use break or continue.

return valid in functions:

func testGuard(){
    guard 2+2 == 4 else {
        print("The universe makes no sense")
        return // this is mandatory!
    }
    print("We can continue with our daily lives")
}

throw valid outside of function as well:

guard 2+2 == 4 else { throw NSError() }

break valid in loops:

for i in 1..<5 {
    guard i < 5 else {
        break
    }
}
like image 128
Dávid Pásztor Avatar answered Oct 13 '22 02:10

Dávid Pásztor