Search code examples
swiftscopeswift3swift-guard

How to tell which block guard exits out of?


When guard fails the condition, they exit the closure. However, what confuses me what is considered to be a block the guard exits out of?

For example, if I have the following:

func doThing() {
  while ... {
    for ... {
      if ... {
        guard ... else { return }
      }
    }
  }
}

Does the guard exit just the if, for, while, or entire func?

What is the actual rule because I've read block and closure terms used interchangeably when defining what the guard exits out of, but each term implicate things differently.


Solution

  • return statement used to exit from nearest closure (function in your case) with result value (Void by default), no matter how deep you are in cycles or if conditions. Probably you mixed up return with break.

    However, you may also use break, continue or throw statement in else clause of guard statement. If you use break statement, for example, you end execution of nearest cycle or switch statement, or, if you mark cycle/if/switch by label and use break followed with that label, you exit marked statement.