For loop in Swift
Aug 21, 2024Ever got stuck with how to perform a repeated task in Swift? Instead of writing the same code multiple times, Swift provides an easy way to do it with loops.
For loop in Swift, also known as for-in loop is used for iterating over collections like arrays, dictionaries, strings and on a specific range of numbers. The execution of the for loop stops when all the elements of the sequence are iterated over, or when a specified condition is met.
You can use for loop to iterate over the classes and collections that you have defined on your own, provided those types conform to the Sequence
protocol.
Table of Contents
- How to use Swift for loop
- Swift for loop with array
- Scope of for loop
- Swift for loop with dictionary
- Swift for loop with Range
- Swift for loop with stride function
- Where Clause in for loop
- Nested for loop
How to use Swift for loop
For loop syntax contains two placeholders, one represents the element that is being accessed and the other one is the sequence on which you want to iterate.
for item in sequence {
// repeating task goes here
}
Here, item
access each element of the sequence
one by one and performs the task defined inside it.
Swift for loop with array
Let's see how to iterate elements of an array with for loop:
let countries = ["India", "Australia", "Canada", "Denmark", "France"]
for countryName in countries {
print(countryName)
}
Output:
India
Australia
Canada
Denmark
France
Scope of for loop
The scope of the variables defined inside a for loop is limited to that for loop only. In case you try to access those variables outside the for loop, you'll get an error.
let numbers = [10, 32, 9, 56, 70]
for number in numbers {
var sum = 0
sum += number
}
print("sum is: \(sum)")
Once you build this code, you will get this error
Cannot find 'sum' in scope
From the error, it's clearly evident that the variables defined inside for loop are not accessible outside the loop block.
Swift For loop with dictionary
Let's see how to iterate elements of a dictionary with for loop:
let numberOfFollowers = ["Martin": 500, "Jared": 250000, "Steve": 15000]
for (name, followersCount) in numberOfFollowers {
print("\(name) has \(followersCount) followers")
}
Output:
Martin has 500 followers
Jared has 250000 followers
Steve has 15000 followers
Each element of the dictionary is returned as a named tuple of key-value pair. In the above example, we have decomposed the tuple's elements as explicitly named constants and used it inside the for loop. You have other ways as well to access the dictionary elements, for example you can use the tuple's element name with .key
and .value
or you can directly access them with index numbers.
Swift For loop with Range
Let's say, you want to perform a specific task 100 times or say starting from 1 to 10. Swift provides the flexibility to loop over a range of numbers with the Range operator. You can use a closed, half-open or one-sided range operators with for loop.
With closed range:
In case of closed range (x...y), the for loop runs y-x+1 times i.e. both the lower and upper endpoints are included.
for element in (1...5) {
print(element)
}
Output:
1
2
3
4
5
If you only want to run the loop based on a specific range but don't want to use each counter value of each iteration, you can instead use a underscore(_) in place of a variable name.
for _ in 1...5 {
print("This will be printed 5 times")
}
Output:
This will be printed 5 times
This will be printed 5 times
This will be printed 5 times
This will be printed 5 times
This will be printed 5 times
With half-open range:
In case of half-open range (x..<y), the for loop runs y-x times i.e. the upper endpoint is excluded.
for element in (1..<5) {
print(element)
}
Output:
1
2
3
4
Swift for loop with stride function
Stride function allows you to loop over numbers present at specific intervals in a range. In the stride(from:to:by:)
function, from
is the starting value of the range, to
is the upper bound (which is excluded) and by indicates the step size to skip in each iteration.
let steps = 2
for element in stride(from: 0, to: 10, by: steps) {
print(element)
}
Output:
0
2
4
6
8
If you want to include the upper bound, you can instead use stride(from:through:by:)
function where to
is replaced with through
and represents the upper bound that is included.
let steps = 2
for element in stride(from: 0, through: 10, by: steps) {
print(element)
}
Output:
0
2
4
6
8
10
Where Clause in for loop
When you use a for loop, by default it iterates over all the elements in the collection or a range of numbers. But, in case you only want a subset from the collection, you can either use a conditional statement inside the for loop or a better option is to use a where clause to filter the elements based on a condition.
Let's say you only want to iterate over even numbers in the array.
let numbers = [10, 32, 9, 56, 70]
for number in numbers where number % 2 == 0 {
print("Number \(number) is even")
}
Output:
Number 10 is even
Number 32 is even
Number 56 is even
Number 70 is even
Nested for loop
You can also use multiple loops inside a for loop. Nested loops comes in handy while working on multi-dimensional array questions in DSA.
for i in 0...3 {
for j in 1...2 {
print("(\(i),\(j))")
}
}
Output:
(0,1)
(0,2)
(1,1)
(1,2)
(2,1)
(2,2)
(3,1)
(3,2)
The first loop iterates from 0 till 3 and for each iteration, the second loop runs twice. The total number of times the loop runs is equal to (number of iterations for first loop * number of iterations for second loop).
Where to go next?
In this article, you learned about for loop, and how it works with ranges and different types of collections. Now, you can do some practice by exploring in which all scenarios you can make use of for loop in your Swift code. We would highly recommend you to read about more related articles like Conditional statements in Swift and Access Control in Swift.