Swift programming for Beginners – Swift while and repeat while Loop

(Swift for Beginners)

Swift while and repeat while Loop

In this article, you will learn to create while and repeat…while loops in Swift programming.

In the previous article, we learned about for-in loop to run a set of tasks for a certain number of times. In this article, you will learn to use while and repeat..while as an alternative of for-in loop when the number of iteration is unknown.

A while loop executes a set of statements until a condition becomes false. These kinds of loops are best used when the number of iterations is not known before the first iteration begins. Swift provides two kinds of while loops:


1. Swift while Loop

This loop evaluates its condition at the start of each pass through the loop.

The syntax of while loop is:

while (TestExpression) {
    // statements
}

How while loop works?

The TestExpression is a boolean expression.

If the TestExpression is evaluated to true,

  • statements inside the while loop are executed.
  • and the TestExpressionis evaluated again.

 

This process goes on until the TestExpression is evaluated to false. If the TestExpression evaluates to false,while loop is terminated.


Flowchart of while Loop

Swift while loop flowchart

Example 1: While Loop

var currentLevel:Int = 0, finalLevel:Int = 5
let gameCompleted = true
while (currentLevel <= finalLevel) {
    //play game
    if gameCompleted {
        print("You have passed level (currentLevel)")
        currentLevel += 1
    }
}
print("outside of while loop")

When you run the program, the output will be:

You have passed level 0
You have passed level 1
You have passed level 2
You have passed level 3
You have passed level 4
You have passed level 5
outside of while loop

In the above program, the variable currentLevel and finalLevel is initialized to 0 and constant gameCompleted is initialized to true.

In each iteration of while loop, it checks the condition currentLevel <= finalLevel. If the condition returns true, statements inside while loop is executed otherwise the loop terminates.

Execution steps
Iteration Condition (currentLevel <= finalLevel) Output
1 0 <= 5 (true) You have passed level 0
2 1 <= 5 (true) You have passed level 1
3 2 <= 5 (true) You have passed level 2
4 3 <= 5 (true) You have passed level 3
5 4 <= 5 (true) You have passed level 4
6 5 <= 5 (true) You have passed level 5
7 6 <= 5 (false) outside of while loop

2. Repeat while Loop

This loop evaluates its condition at the end of each pass through the loop.The repeat…while loop is similar to while loop with one key difference. The body of repeat…while loop is executed once before the test expression is checked.

The syntax of repeat..while loop is:

repeat {
    // statements
    ...
} while (testExpression)

How repeat…while loop works?

The body of repeat…while loop is executed once (before checking the test expression). Only then, testExpression is checked.

If testExpression is evaluated to true, statements inside the body of the loop are executed, and testExpression is evaluated again. This process goes on until testExpression is evaluated to false.

When testExpression is false, the repeat..while loop terminates.


Flowchart of repeat…while Loop

Swift repeat..while loop flowchart

Example 2: Repeat while Loop

var currentLevel:Int = 0, finalLevel:Int = 5
let gameCompleted = true
repeat {
    //play game
    if gameCompleted {
        print("You have passed level (currentLevel)")
        currentLevel += 1
    }
} while (currentLevel <= finalLevel)
print("outside of repeat while loop")

When you run the program, the output will be:

You have passed level 0
You have passed level 1
You have passed level 2
You have passed level 3
You have passed level 4
You have passed level 5
outside of repeat while loop

In the above example, for the first time the statements inside the loop executes. And for next iteration, it checks the condition currentLevel <= finalLevel.

If the condition returns true, statements inside while loop is executed otherwise the loop terminates.

Execution steps
Iteration Condition (currentLevel <= finalLevel) Output
1 0 <= 5 (true) You have passed level 0
2 1 <= 5 (true) You have passed level 1
3 2 <= 5 (true) You have passed level 2
4 3 <= 5 (true) You have passed level 3
5 4 <= 5 (true) You have passed level 4
6 5 <= 5 (true) You have passed level 5
7 6 <= 5 (false) outside of repeat while loop

Although both while and repeat while loop have same execution steps, the condition currentLevel <= finalLevel on repeat while loop is executed only after executing the statements inside it.

But in while, the condition is checked at the beginning before executing the statements inside it.


3. Infinite while Loop

If the test expression never evaluates to false, the body of while and repeat..while loop is executed infinite number of times.

Example 3: Infinite while Loop

while (true) {
   print("Hello, World!")
}

 

repeat {
   print("Hello, World!")

} while (true)

When you run the program, the output will be:

Hello, World!
Hello, World!
.
.
.

When you run the program, both loop executes print("Hello, World!") statement for infinite number of times. So, you can see continuous output Hello, World! in the console.

 

 

Swift programming for Beginners – Swift while and repeat while Loop

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!