Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Swift – While Loop

  • Last Updated : 23 Nov, 2021

Just like other programming languages, the working of the while loop in Swift is also the same. It is used to execute a target statement repeatedly as long as a given condition is true. And when the condition becomes false, the loop will immediately break and the line after the loop will execute. While loops are used as an alternative to for-in loops when the number of iteration is not known. This loop executes a set of statements until a false condition occurs. This loop is generally used when we don’t know the number of iterations. That means when we don’t know how many times we have to loop we will use while loop their instead of for loop because this loop will repeat the code as long as the condition is true.

Syntax:

while condition 
{
    // Body or while loop
    Statement
}

Where the condition may be an expression like x > 2 and statement(s) may be a single line of code or multiple lines of code.

Flow chart of while loop:

while loop in swift

flow diagram

Example 1: 

Swift




// Swift program to print GeeksforGeeks
// 7 times 
  
// Creating and initializing variable
var i = 2
  
// Iterate the while loop till i<8
while i < 8{
    print("GeeksforGeeks")
    i = i + 1
}

Output:

GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Example 2:

Swift




// Swift program to print the even and
// odd numbers using while loop
  
// Creating and initializing variables
var i = 1, n = 20
  
// Iterate the while loop 
print("Even numbers:")
while i <= n{
  
    // It will check the number is 
    // completely divisible by 2 or not
    if (i % 2 == 0)
    {
        print(i)
    }
    i = i + 1
}

Output:

Even numbers:
2
4
6
8
10
12
14
16
18
20

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!