swiftguard

How to exit GUARD outside and inside a function - Swift


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?


Solution

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