Table of contents
1.
Introduction
2.
Loops in Swift
2.1.
While loop:
2.2.
For-in loop:
2.3.
Repeat-while loop:
3.
Swift while loop 
3.1.
Syntax:
3.2.
Flowchart of While loop
3.3.
Example:
3.4.
Output:
4.
Swift for-in loop
4.1.
Syntax:
4.2.
Flowchart of a for-in loop
4.3.
Example 1: Loop Over Array
4.4.
Output:
4.5.
Example 2: for loop with where Clause
4.6.
Output:
4.7.
Example 3: for loop With Range
4.8.
Output:
4.9.
Example 4: for Loop with Stride Function
4.10.
Output:
5.
Swift repeat-while loop
5.1.
Syntax:
5.2.
Flow chart of repeat-while loop
5.3.
Example:
5.4.
Output:
6.
Frequently Asked Questions
6.1.
Why are loops required?
6.2.
Is the do-while loop is same as the repeat-while in Swift?
6.3.
What is the most common problem with loops?
6.4.
What are the advantages of utilizing loops?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Swift Loops for-in, while, repeat-while

Author Ayush Mishra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Occasionally, while programming, we run into a task that requires us to work with large amounts of data, such as a list of 50 or even 5000 items.

Is there a way to make this task easier so you don't have to write everything down by hand? Manually typing everything would undoubtedly take a long time. Here's where loops come in handy.

This blog will go through how to use the for-in, while, and repeat-while loops in Swift to enable the program to repeat specific tasks and fulfill critical functions interactions with applications.

Iteration is done via a loop, and iteration signifies recurrence. We can accomplish anything n times by using loops. A loop can go on indefinitely until the condition is met. We write a necessity to break the loop in general.

For example, if we use a loop to output Coding Ninjas Studio 20 times, we must now provide a condition n=20 types of things in the loop. The loop breaks after 21 iterations.

Loops in Swift

While loop:

The while loop is a programming construct that repeats a block of code an undetermined number of times until a condition is fulfilled.

For-in loop:

The for-in loop is a simple control statement that lets you loop over an object's attributes. For each property of the object, the statements of code present within the loop body will be run once.

Repeat-while loop:

The repeat-while loop is very similar to the while loop in Swift, with the exception that it will run the defined statements first, then conduct the condition check, and then execute the statements repeatedly until the defined condition is met.

Swift while loop 

The while loop in Swift works the same as it does in other programming languages. It is used to keep running a target statement as long as a condition is actual. When the state is false, the loop will terminate, and the line following the loop will execute. This loop executes a series of statements until it encounters a faulty condition. This loop is commonly used when the number of iterations is unknown.

Syntax:

    while (TestExpression)
       {     
        // statements        
       }

 

In this case, TestExpression is a Boolean expression. If it is true,

  • The while loop executes the statements inside it.
  • The TestExpression is then evaluated once more.

This continues until the test expression returns false. The while loop ends when the TestExpression encounters the faulty condition.

Flowchart of While loop

 

Example:

var j = 3
  
// Iterate the while loop till j<50
While j < 6{
    print("Coding Ninjas Studio")
    j = j + 1
}

Output:

Coding Ninjas Studio
Coding Ninjas Studio
Coding Ninjas Studio

 

The while loop is executed in the preceding program until the condition is evaluated as false, and it quits as soon as it receives the false condition.

Swift for-in loop

The for-in loop in Swift is used to repeat a piece of code a specific number of times. It can iterate through any sequence, including an array, a range, a string, etc. 

Syntax:

for index in var
 {
// statement
}

Flowchart of a for-in loop

 

Example 1: Loop Over Array

let lang = ["C", "C++", "Swift", "JavaScript"]

for l in lang {
      print(l)
}

Output:

C
C++
Swift
Javascript

 

We built an array called lang in the previous example.

The value ofis first set to the first element of the array, Swift, which produce the print statement inside the loop to be run.

The print statement is called again when the l has been updated with the next element of the array. The loop will continue until the array's last segment is accessed.

Example 2: for loop with where Clause

With a for-in loop in Swift, we can easily include a where Clause. It's used in the loop to implement filters. The loop will execute if the condition where Clause returns true.

// remove C from an array

let lang  = ["C", "C++", "Java", "Python"]

for lan in lang where lan != "C"{
  print(lang) 
}

Output:

C++
Java
Python

 

The code written inside the loop will run if the condition inside where Clause returns true. Otherwise, it will not be carried out.

Example 3: for loop With Range

A range is a collection of values that fall between two numerical intervals.

// iterate from i = 1 to 1 = 7
for i in 1...7 {
    print(i)
}

Output:

1
2
3
4
5
6
7

 

The for-in loop was used to iterate over a range of 1 to 3 in the preceding example.

Example 4: for Loop with Stride Function

Instead of range, we must use the stride(from:to:by) function if we want a loop to increment by a fixed value in each iteration.

for j in stride(from: 1, to: 8, by: 2) {
    print(j)
}

Output:

1
3
5
7

 

The loop iterates over the Range of 1 to 8 with an interval of 2 in the example above. The number 8 is not included in the series, though.

Swift repeat-while loop

The repeat-while loop is used in Swift to repeatedly execute a block of code or a series of statements. The repeat-while loop is very similar to the while loop with the exception that it will run the statements at least once even if the condition is FALSE because it will execute the body first and then check the state. In contrast, the while loop will only run the statements when the form is TRUE.

Syntax:

repeat 
{
    // statements
 
} while (condition)

 

The repeat-while loop in Swift is equivalent to the do-while loop in other programming languages.

Flow chart of repeat-while loop

 

Example:

var i = 1, n = 8
// repeat...while loop from 1 to 8
repeat {
  print(i)
  i = i + 1
} while (i <= n)

Output:

1
2
3
4
5
6
7
8

Frequently Asked Questions

Why are loops required?

Loops are computer constructs that repeat a code section until the desired process is completed. Loops are vital for saving time and minimizing errors in programming since repetitive operations are expected.

Is the do-while loop is same as the repeat-while in Swift?

Yes, both are the same. Both loop body guaranteed to execute at least once.

What is the most common problem with loops?

Another typical mistake when constructing loops is to create a loop that never ends. An infinite loop is what this is known as. If your program contains an endless loop, it may display the same output repeatedly.

What are the advantages of utilizing loops?

A loop is used in computer programming to run a set of instructions or a block of code several times without writing it again.

Conclusion

The concept of Swift loops has been thoroughly covered in this article. We began with an overview of Swift loops and then went over each loop form in detail, complete with explanations, code, and output statements.

We hope that this blog has improved your understanding of Swift loops. If you would like to learn more, check out our blogs, the Definitive Swift Tutorial for Beginnerswhy iOS & OS X Developers choose Swift? and which is better to learn? iOS or Android?

Happy learning!

Live masterclass