Swift Repeat/While Loop

Swift Repeat/While Loop

Use repeat { ... } while condition to run the body at least once.


Repeat/while Loop Example

This example uses a repeat/while loop to print “Try #1” and “Try #2”.

Example

var attempts = 0
repeat {
  attempts += 1
  print("Attempt #\(attempts)")
} while attempts < 3

This example demonstrates repeat (do-while style).

Tip: Avoid infinite loops. Ensure the loop condition will eventually become false.


REMOVE ADS


Runs Once Even If Condition Is False

Because repeat checks the condition after the body, it executes at least once.

Example

var n = 0
repeat {
  print("Runs once")
} while n > 0

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *