Swift - Loops



Swift loops are used to execute a block of code repeatedly, either for a specific number of times or until a certain condition is met.

Swift Control Statement (Loops)

Swift loop statements allow us to execute a statement or group of statements multiple times. They execute in a sequential manner like the first statement in a function is executed first, followed by the second, and so on. A loop can run infinite times until the given condition is false.

For example, we want to print a series of numbers from 1 to 10. So to print the sequence we can specify 110 range in the for-in loop and the loop ends when it encounters 10. Following is the general form of a loop statement in most programming languages −

Swift Loops

Types of Loops in Swift

The following are the different loop types in Swift programming language:

Loop Name Description
for-in Iterates through each element of the given sequence or collection such as array, ranges, etc. and can perform operation on them if needed.
while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
repeat...while loop Like a while statement, except that it tests the condition at the end of the loop body.

1. The for-in Loop

The for-in loop iterates over a sequence like arrays, ranges, dictionaries, or strings.

The following is the syntax of for in loop:

for item in sequence {
    // Code to execute
}

Example

The following example demonstrates the use of for in loop:

import Foundation

let numbers = [1, 2, 3, 4, 5]

for number in numbers {
    print("Number is \(number)")
}

It will produce the following output −

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5

2. The while Loop

The while loop repeats a block of code as long as a given condition is true.

The following is the syntax of while in loop:

while condition {
    // Code to execute
}

Example

The following example demonstrates the use of while loop:

import Foundation

var count = 1

while count <= 5 {
    print("Count is \(count)")
    count += 1
}

It will produce the following output −

Count is 1
Count is 2
Count is 3
Count is 4
Count is 5

3. The repeat-while Loop

The repeat-while loop is similar to the while loop, but it evaluates the condition after executing the loop body. That means the block of code will execute at least once.

The following is the syntax of repeat-while loop:

repeat {
    // Code to execute
} while condition

Example

The following example demonstrates the use of repeat-while loop:

import Foundation

var index = 1

repeat {
    print("Index is \(index)")
    index += 1
} while index <= 5

It will produce the following output −

Index is 1
Index is 2
Index is 3
Index is 4
Index is 5

Swift - Loop Control Statements

Loop control statements allow the developer to change the execution of loops from its normal sequence. They are designed to transfer controls from one block of statements to another. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Swift supports the following control statements −

Control Statement Description
continue statement This statement tells a loop to terminate what it is doing and start again at the beginning of the next iteration through the loop.
break statement Terminates the loop statement and transfers execution to the statement immediately following the loop.
fallthrough statement The fall through statement simulates the behavior of Swift 4 switch to C-style switch.

Example

Swift program to demonstrate the use of break statement in a for-in loop.

import Foundation
print("Numbers:")
for y in 1...8 {
   if y == 5 {
    
      // When y is equal to 5 the loop will terminate
      break
   }
   print(y)
}
print("Hello Swift")

It will produce the following output −

Numbers:
1
2
3
4
Hello Swift

Swift Multiple Loops

You can also use multiple loops one after another to perform different iterations in sequence. Each loop runs independently and is executed based on its own condition or range.

Example

The following example demonstrates how you can use multiple loops in a program:

import Foundation

print("Counting 1 to 3:")
for i in 1...3 {
    print(i)
}

print("Counting 10 to 12:")
for j in 10...12 {
    print(j)
}

It will produce the following output −

Counting 1 to 3:
1
2
3
Counting 10 to 12:
10
11
12

Swift Nested Loops

A nested loop means using one loop inside another loop. The nested loops are commonly used for working with multi-dimensional data structures or patterns where each outer iteration runs a complete inner loop.

Example

The following example demonstrates how you can use the nested loops:

import Foundation

for i in 1...3 {
    for j in 1...2 {
        print("i = \(i), j = \(j)")
    }
}

It will produce the following output −

i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
Advertisements