OneBite.Dev - Coding blog in a bite size

Do A While Loop In Swift

Code snippet for how to Do A While Loop In Swift with sample and detail explanation

Swift is a robust and intuitive programming language developed by Apple for iOS, macOS, watchOS, and beyond. To perform a set of statements until a condition becomes false, the ‘do while’ loop is used. Swift’s version of ‘do while’ loop is actually a ‘repeat while’ loop.

Code snippet for Do A While Loop

Let’s look at a simple code snippet for a ‘do while’ loop in Swift.

var i = 1

repeat {
    print("i is \(i)")
    i += 1
} while i <= 10

Code Explanation for Do A While Loop

In the above code, we start off by declaring a variable i and assigning it a value of 1.

The repeat keyword initiates the ‘do while’ loop. Inside this loop, we have a print statement that prints the current value of i. After the print statement, we have i += 1 which is a shorthand operation for i = i + 1, i.e., it increments the value of i by 1.

The incrementing of the variable i and the print statement will keep repeating as long as the condition, specified after the while keyword, is true. In our case, the condition is i <= 10. Hence, the loop will keep running until the value of i is less than or equal to 10.

Essentially, the ‘do while’ loop, or ‘repeat while’ as it is called in Swift, executes the block of code once before checking the condition. If the condition is true, the code block is executed again and this continues until the condition finally becomes false.

Please note that the ‘do while’ loop is different from the ‘while’ loop in that the ‘do while’ loop will execute its block of code at least once, regardless of the condition, whereas the ‘while’ loop will only execute its code block if its condition is true from the start.

swift