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?
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.
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.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With