> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Swift While Loop

A `while` loop is a control flow statement that repeatedly executes a block of code as long as a specified boolean condition evaluates to `true`. Swift provides two variants of this construct: the standard `while` loop, which evaluates its condition prior to each iteration, and the `repeat-while` loop, which evaluates its condition after each iteration.

## Standard `while` Loop

The standard `while` loop evaluates its condition at the start of each pass through the loop.

```swift theme={"dark"}
while condition {
    // statements to execute
}
```

**Execution Mechanics:**

1. The `condition` expression is evaluated.
2. If the condition evaluates to `true`, the statements within the loop body are executed.
3. Upon reaching the closing brace, control flow returns to step 1.
4. If the condition evaluates to `false`, the loop terminates immediately, and execution resumes at the first statement following the loop's closing brace.

Because the condition is evaluated before the loop body executes, it is possible for the statements inside a standard `while` loop to execute zero times if the initial condition is `false`.

## `repeat-while` Loop

The `repeat-while` loop (analogous to the `do-while` loop in C-based languages) performs a single pass through the loop block before evaluating its condition.

```swift theme={"dark"}
repeat {
    // statements to execute
} while condition
```

**Execution Mechanics:**

1. The statements within the `repeat` block are executed unconditionally.
2. The `condition` expression is evaluated.
3. If the condition evaluates to `true`, control flow jumps back to step 1.
4. If the condition evaluates to `false`, the loop terminates.

This structure guarantees that the loop body will execute at least once, regardless of the condition's initial state.

## Condition Evaluation and Compound Conditions

Swift enforces strict type safety for loop conditions. A standard condition expression must evaluate explicitly to a `Bool` type. Attempting to use non-boolean values, such as integers (e.g., `while 1`), will result in a compile-time error.

Swift also supports compound condition lists. A `while` loop can evaluate multiple conditions separated by commas. These conditions evaluate sequentially from left to right and short-circuit; if any condition evaluates to `false` or `nil`, the entire condition list evaluates to `false`, and the loop terminates immediately without evaluating the remaining conditions.

```swift theme={"dark"}
while conditionA, let value = optionalExpression, value > 0 {
    // Executes as long as conditionA is true, optionalExpression is not nil, 
    // and the unwrapped value is greater than 0.
}
```

## Optional Binding and Pattern Matching

Swift extends the `while` loop with optional binding (`while let` and `while var`) and pattern matching (`while case`), allowing loops to iterate based on the presence or structure of data.

**Optional Binding:** Iterates continuously as long as an optional expression returns a non-`nil` value. The value is unwrapped and assigned to a local constant or variable for the duration of the loop iteration.

```swift theme={"dark"}
while let unwrappedValue = optionalExpression {
    // statements to execute using 'unwrappedValue'
}
```

**Pattern Matching:** Iterates as long as the evaluated expression matches a specific pattern, such as an enumeration case with associated values.

```swift theme={"dark"}
while case .someCase(let associatedValue) = enumExpression {
    // statements to execute using 'associatedValue'
}
```

## Control Transfer Statements

Execution within a `while` or `repeat-while` loop can be manually altered using control transfer statements:

* **`continue`**: Immediately halts the current iteration, skipping any remaining statements in the loop body. Control flow is transferred directly to the condition evaluation to determine if the next iteration should begin.
* **`break`**: Immediately terminates the innermost enclosing loop *or `switch` statement*. No further iterations occur, the condition is not re-evaluated, and control flow transfers to the code immediately following the terminated construct.

```swift theme={"dark"}
while conditionA {
    if conditionB {
        continue // Skips to the next evaluation of conditionA
    }
    
    if conditionC {
        break // Exits the loop entirely
    }
}
```

## Labeled Statements

When working with nested loops or `switch` statements within loops, Swift allows the use of statement labels to explicitly define which construct a `break` or `continue` statement targets.

Because an unlabeled `break` terminates the innermost enclosing loop *or `switch` statement*, using an unlabeled `break` inside a `switch` that is nested within a `while` loop will only terminate the `switch`. A labeled `break` is strictly required to exit the enclosing `while` loop from within the nested `switch`.

```swift theme={"dark"}
outerLoop: while conditionA {
    switch someValue {
    case matchA:
        break // Terminates the switch statement only; the while loop continues
    case matchB:
        break outerLoop // Terminates the while loop entirely
    default:
        continue outerLoop // Skips to the next iteration of the while loop
    }
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Swift Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
