Understanding Swift loops


Introduction to Loops In Swift

Loops are fundamental programming constructs that allow us to execute a block of code multiple times. In Swift, loops help automate repetitive tasks, improving code efficiency and readability. They operate sequentially, ensuring that each statement runs in order until a specific condition is met.

For in loop





The for-in loop in Swift is a powerful control flow statement that allows iteration over collections such as arrays, sets, dictionaries, and ranges. Unlike traditional loops, it eliminates the need for explicit index manipulation, making the code more readable and efficient.

This loop seamlessly integrates with Swift’s functional programming paradigm, enabling the use of higher-order functions like map(), filter(), and reduce().

Syntax of for-in Loop

for variable in collection {
// Code to execute in each iteration
}

Example: Iterating Over an Array

import Foundation

let numbers = [ 10 , 20, 30, 40, 50]
for num in numbers {
print ( "Current number: \(num) " )
}

Output

Current number: 10
Current number: 20
Current number: 30
Current number: 40
Current number: 50

Ignoring Values with Underscore (_)

When iteration is required without using the values, Swift provides _ (underscore) as a placeholder.

import Foundation

for _ in 1...5 {
print ( "Hello, Swift!" )
}

Output

Hello, Swift!
Hello, Swift!
Hello, Swift!
Hello, Swift!
Hello, Swift!

Using Ranges with for-in Loop

Swift allows iteration over numeric ranges using both closed (...) and half-open (..<) range operators.

import Foundation

print ( "Using Closed Range:" )
for num in 1...5 {
print (num)
}
print ( "\nUsing Half-Open Range:" )
for num in 1..<5 {
print (num)
}

Output

Using Closed Range:
1
2
3
4
5

Using Half-Open Range:
1
2
3
4

Using stride() for Custom Steps

The stride() function enables iteration with custom step sizes in both ascending and descending order.

import Foundation

print ( "Ascending Order:" )
for num in stride(from: 1, to: 10, by: 2) {
print (num)
}
print ( "\nDescending Order:" )
for num in stride(from: 10, to: 1, by: -2) {
print (num)
}

Output

Ascending Order:
1
3
5
7
9

Descending Order:
10
8
6
4
2

Filtering with where Clause

The where clause allows filtering elements within the for-in loop, ensuring only specific conditions are met.

import Foundation

let numbers = [45, 22, 67, 34, 89, 90]
print ( "Even Numbers:" )
for num in numbers where num % 2 == 0 {
print (num)
}

Output

Even Numbers:
22
34
90