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

2

8

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?

Averyaveryl answered 4/12, 2017 at 17:5 Comment(0)
E
13

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
    }
}

continue valid in loops:

for someObject in someArray { 
    guard let someProperty = someObject.someOptionalProperty else { 
        continue 
    } 
}
Emalee answered 4/12, 2017 at 17:11 Comment(2)
Perfect, thank you very much for teaching!Averyaveryl
you for got to add in continue as in for someObject in someArray { guard let someProperty = someObject.someOptionalProperty else { continue } }. I upvoted your answer btw, it was very helpful for the throw NSError()Teen
L
7

Or is GUARD only used within functions?

Not necessarily.

From the documentation:

If that condition is not met, the code inside the else branch is executed. That branch must transfer control to exit the code block in which the guard statement appears. It can do this with a control transfer statement such as return, break, continue, or throw, or it can call a function or method that doesn’t return, such as fatalError(_:file:line:).

For example this can be used in a Playgound on the top level

for i in 0...10 {
    guard i % 2 == 0 else { continue }
    print(i)
}

The error message is actually not related to guard. It just states that return cannot be used outside of a func

Lundell answered 4/12, 2017 at 17:15 Comment(1)
I appreciate your response, it helped me a lot for my learning, greetings!Averyaveryl

© 2022 - 2024 — McMap. All rights reserved.