Blog / January 31, 2023 / 3 mins read / By Mahi Garg

Do While (Repeat While) Loop in Swift

Swift is a powerful and expressive programming language that offers a variety of loop structures to handle repetitive tasks efficiently. Among these, the do-while loop stands out as a loop that ensures the code inside the loop executes at least once, regardless of the loop’s condition. In this blog, we will explore the do-while loop in Swift, its syntax, and examples to showcase its usefulness in different scenarios.

Introducing the do-while Loop

The do-while loop, also known as the repeat-while loop, is a control flow statement that iterates over a block of code while a specified condition remains true. The unique feature of the do-while loop is that it guarantees the code inside the loop is executed at least once, even if the condition evaluates to false from the beginning.

Syntax of the do-while Loop

The basic syntax of the do-while loop in Swift is as follows:

do {
    // Code to be executed at least once
} while condition

The condition is a Boolean expression that determines whether the loop should continue iterating or terminate. The block of code inside the do section is executed first, and then the condition is checked. If the condition evaluates to true, the loop repeats; otherwise, the loop terminates.

Examples of do-while Loop

Example 1 - Rolling a Dice:
import Foundation

var diceValue: Int

repeat {
    diceValue = Int.random(in: 1...6)
    print("You rolled a \(diceValue)")
} while diceValue != 6

In this example, the do-while loop simulates rolling a dice. The loop continues to roll the dice and print the result until the dice rolls a value of 6. Since the condition is checked after the loop body, the loop always rolls the dice at least once, guaranteeing that the player gets a result.

Example 2 - Reading User Input:
var input: String

repeat {
    print("Please enter a positive number:")
    input = readLine() ?? ""
} while Double(input) == nil || Double(input)! <= 0

let number = Double(input)!
print("The square root of \(number) is \(sqrt(number))")

In this example, the do-while loop prompts the user to enter a positive number repeatedly until a valid positive number is provided. The loop checks whether the input can be converted to a valid positive number (not nil and greater than 0) before proceeding with the computation and printing the square root.

Loop Control and Infinite do-while Loops

As with any loop structure, you must exercise caution to avoid creating infinite loops that never terminate. An infinite do-while loop can be created by using a condition that always evaluates to true. For example:

// Infinite Loop
repeat {
    // Code that keeps executing indefinitely
} while true

To prevent infinite loops, ensure that the loop condition eventually evaluates to false based on the progression of your loop.

Conclusion

The do-while loop in Swift is a powerful and flexible tool that allows you to handle repetitive tasks, ensuring that the loop body executes at least once, regardless of the loop’s condition. With the examples provided in this blog, you can now apply the do-while loop effectively in various scenarios, such as input validation, randomization, and more.

Always use loop control statements like break and continue judiciously to manage the flow of your loops, and avoid creating infinite loops that may cause your program to hang or crash. Embrace the power of the do-while loop in Swift and elevate your programming skills to new heights. Happy coding! 🚀

Comments