0
0
Swiftprogramming~5 mins

Repeat-while loop in Swift

Choose your learning style9 modes available
Introduction

A repeat-while loop helps you run a set of instructions at least once, then keep repeating them while a condition is true.

When you want to ask a question and repeat it until the answer is correct.
When you need to perform an action first, then check if you should do it again.
When you want to keep trying something until it works, but you must try at least once.
When you want to count or collect input from a user until a stop condition is met.
Syntax
Swift
repeat {
    // code to run
} while condition

The code inside repeat runs first, then the condition is checked.

If the condition is true, the loop runs again; if false, it stops.

Examples
This prints numbers 1 to 3, increasing count each time.
Swift
var count = 1
repeat {
    print("Count is \(count)")
    count += 1
} while count <= 3
This asks the user to type 'yes' and repeats until they do.
Swift
var input: String
repeat {
    print("Enter 'yes' to stop:", terminator: " ")
    input = readLine() ?? ""
} while input.lowercased() != "yes"
Sample Program

This program counts down from 5 to 1, printing each number.

Swift
var number = 5
repeat {
    print("Number is \(number)")
    number -= 1
} while number > 0
OutputSuccess
Important Notes

The repeat-while loop always runs the code inside at least once, even if the condition is false at the start.

Use repeat-while when you want to guarantee the loop runs before checking the condition.

Summary

Repeat-while loops run code first, then check if they should repeat.

They are useful when the code must run at least once.

Use them to repeat actions until a condition becomes false.