In Swift, how do you leave an inner and an outer loop at once, and what does an unlabeled break inside a switch end?
answer
- name the statement, then jump to it
- label followed by a colon
- innermost loop or switch only
- continue resumes the labeled loop
basics
~20 sLabel the outer loop and write break with that label to leave every nested loop at once. An unlabeled break ends only the innermost loop or switch, so in a switch inside a loop the loop carries on.
solid answer
~40 sSwift lets you prefix a loop, an `if`, a `switch` or a `do` statement with a label such as `retry:`. `break retry` ends the statement with that label, however deeply nested the `break` is, and `continue retry` ends the current pass of the labeled loop and moves it to its next pass. Without a label, `break` ends the innermost enclosing loop or `switch` and `continue` the innermost loop. The trap is a `switch` inside a loop: a plain `break` in a case only ends the `switch`, so the loop keeps going - you need `break` with the loop's label. The compiler backs this up: an unlabeled `break` cannot leave an `if` or `do`, `continue` cannot target a `switch`, and an inner statement cannot reuse an outer label's name.
code
swift · 30 linesenum SendResult { case sent, transient, poisoned }
func send(_ item: Int, attempt: Int) -> SendResult {
if item < 0 { return .poisoned }
if item == 5 && attempt == 1 { return .transient }
return .sent
}
let batches = [[1, 2, 3], [4, 5, 6], [7, -8, 9]]
var attempt = 0
retry: while attempt < 3 {
attempt += 1
print("attempt \(attempt)")
for batch in batches {
for item in batch {
switch send(item, attempt: attempt) {
case .sent:
break // ends the switch only
case .transient:
continue retry // abandon this pass, start a new attempt
case .poisoned:
print("poisoned item \(item), stopping every loop")
break retry // leave all three loops at once
}
}
}
break // every batch went through
}
print("done after \(attempt) attempt(s)")go deeper
Recall that break ends a loop or switch, continue skips to the next pass, and a label lets either target an outer loop.
Explain what an unlabeled break ends inside a switch within a loop, and use break and continue with a label to control nested loops precisely.
Catch the silent switch-break bug in review, and judge when a label is clearer than extracting the nested search into a function that returns.
No team policy hangs on labels; the lead's concern is readable control flow, so prefer whichever of a label or a returning function states the exit most plainly.
## What a statement label is A **statement label** is a name followed by a colon written in front of a statement: ```swift retry: while attempt < 3 { ... } ``` Swift accepts a label on four kinds of statement: loops (`for`-`in`, `while`, `repeat`-`while`), `if`, `switch` and `do`. The label's scope is the whole labeled statement, and its only use is as the target of `break` and `continue`. Labels cannot go on other statements; putting one on a `guard`, for example, fails with "labels are only valid on loops, if, and switch statements" (the message does not list `do`, although the Swift 6.4 compiler accepts a labeled `do`). ## `break` and `continue`, with and without a label | Statement | What it ends | Where execution resumes | |---|---|---| | `break` | the innermost enclosing loop or `switch` | the first statement after it | | `break label` | the labeled loop, `if`, `switch` or `do` | the first statement after that labeled statement | | `continue` | the current pass of the innermost loop | that loop's next pass | | `continue label` | the current pass of the labeled loop, abandoning any inner loops | the labeled loop's next pass | Two consequences matter in practice: - `continue` never applies to a `switch`. A plain `continue` inside a case refers to the enclosing loop, and `continue` with the label of a `switch` fails with "'continue' cannot be used with switch statements". - An unlabeled `break` cannot leave an `if` or a `do`. Write one there and the compiler says "unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do". ## The switch-inside-a-loop trap Swift `switch` cases do not fall through, so a `break` in a case is rarely needed - except to give a case an empty body or to leave it early. That makes it easy to forget that `break` inside a `switch` belongs to the `switch`: ```swift for item in [1, 2, -1, 3] { switch item { case ..<0: break // ends the switch, not the loop default: seen.append(item) } } // seen == [1, 2, 3]: the loop kept going after -1 ``` If the intent was "stop at the first negative item", this code is wrong and compiles cleanly. The fix is to label the loop and write `break` with that label. ## A retry loop over nested batches Consider an uploader that sends items in batches and retries the whole run on a transient failure, but must stop every loop the moment it meets an item that can never succeed. Three loops are nested - attempts, batches, items - and the decision is made inside a `switch` in the innermost one: ```swift retry: while attempt < 3 { attempt += 1 for batch in batches { for item in batch { switch send(item, attempt: attempt) { case .sent: break // ends the switch only case .transient: continue retry // abandon this pass, start a new attempt case .poisoned: break retry // leave all three loops at once } } } break // every batch went through } ``` `continue retry` abandons both inner loops and starts the next pass of the `while`, re-checking `attempt < 3`. `break retry` ends the `while` itself, and control resumes after it. Without labels, the same logic needs a Boolean flag checked after each loop, which is easy to get wrong when a fourth level is added. ## Compiler rules worth knowing 1. A nested statement cannot reuse the label of a statement that encloses it. Doing so fails with "label 'outer' cannot be reused on an inner statement". 2. A `break` or `continue` that names a label not in scope fails with "cannot find label ... in scope". 3. `continue` with a label must name a loop; `break` with a label may name any labeled statement. 4. A label is an identifier, so the usual identifier rules apply; there is no special label syntax beyond the colon. ## When a function is clearer than a label Labels are the direct answer to "leave two loops at once", and interviewers expect candidates to know them. In review, though, a search over nested loops often reads better extracted into a function that simply `return`s the result when it finds it - the return ends every loop and states the outcome in one line. Labels earn their place when the loop body must carry on after the nested loops, as in the retry example, where a function boundary would split shared state.
- What happens if you write continue inside a switch case that sits in a for loop?It refers to the loop, not the switch: `continue` never applies to a `switch`, so it ends the current pass of the innermost enclosing loop and moves on to the next element. Naming a labeled `switch` after `continue` is a compile error.
- Can you use break to leave an if statement early?Only with a label. Labeling the `if` (`check: if ready { ... break check ... }`) lets `break check` jump past the rest of its body. An unlabeled `break` inside an `if` that is not within a loop or `switch` is a compile error, because unlabeled `break` only applies to loops and `switch`.
- An unlabeled break inside a switch also ends the enclosing loop
- Swift needs a Boolean flag to leave two nested loops
- continue can target a labeled switch statement
- Only for-in loops can carry a statement label
- An unlabeled break can end an if statement early