Skip to main content
The repeat-while loop in Swift is a post-test control flow statement that executes a block of code at least once before evaluating its termination condition. It is Swift’s equivalent to the do-while loop found in C-based languages.

Syntax

Execution Flow

  1. Unconditional Execution: The program enters the repeat block and executes the enclosed statements sequentially. This first pass happens regardless of the state of the condition.
  2. Condition Evaluation: Upon reaching the while clause at the end of the block, the boolean condition is evaluated.
  3. Branching:
    • If the condition evaluates to true, control flow jumps back to the beginning of the repeat block for another iteration.
    • If the condition evaluates to false, the loop terminates, and control flow proceeds to the next statement immediately following the loop structure.

Code Example

Technical Characteristics

  • Post-Condition Evaluation: Because the condition is evaluated at the end of the loop rather than the beginning (pre-test), the loop body is structurally guaranteed a minimum of one execution.
  • Strict Boolean Requirement: The expression provided to the while clause must evaluate explicitly to a Bool type (true or false). Swift’s type safety prevents implicit type coercion; passing an integer (like 1 or 0) or an optional will result in a compile-time error.
  • Variable Scope: Variables declared inside the repeat block are scoped locally to that block and are not accessible within the while condition clause. To evaluate a variable in the while condition, it must be declared in the outer scope prior to the repeat keyword.

Scope Example

Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More