Swift For Loop
Introduction
The for
loop is one of the most common control flow statements in Swift programming. It allows you to execute a block of code repeatedly for a specified number of times or to iterate through elements in a collection such as arrays, dictionaries, ranges, and strings. For loops in Swift are designed to be safe and efficient, helping you avoid common programming errors like off-by-one errors or index out-of-bounds exceptions.
In this tutorial, we'll explore how to use for loops in Swift, starting with the basics and moving on to more advanced use cases.
Basic For Loop Syntax
The most common form of a for loop in Swift uses the for-in
syntax to iterate over a sequence:
for item in sequence {
// Code to be executed for each item
}
Where:
item
is a constant that represents the current element in each iterationsequence
is a collection or range to iterate through
Iterating Through Ranges
Closed Range Operator
Swift provides a convenient way to iterate through a range of numbers using the closed range operator (...
):
// Print numbers from 1 to 5
for number in 1...5 {
print(number)
}
Output:
1
2
3
4
5
Half-Open Range Operator
If you want to exclude the upper bound, you can use the half-open range operator (..<
):
// Print numbers from 1 to 4
for number in 1..<5 {
print(number)
}
Output:
1
2
3
4
One-Sided Range
Swift also supports one-sided ranges for when you want to iterate from a value to the end of a collection:
let names = ["Anna", "Brian", "Craig", "Donna", "Eric"]
// Iterate from index 2 to the end
for name in names[2...] {
print(name)
}
Output:
Craig
Donna
Eric
Or from the beginning up to a certain index:
// Iterate from the beginning to index 2
for name in names[..<3] {
print(name)
}
Output:
Anna
Brian
Craig
Iterating Through Collections
Arrays
let fruits = ["Apple", "Banana", "Orange", "Mango", "Strawberry"]
for fruit in fruits {
print("I like \(fruit)s")
}
Output:
I like Apples
I like Bananas
I like Oranges
I like Mangos
I like Strawberrys
Dictionaries
When you iterate through a dictionary, each item is returned as a key-value tuple:
let studentScores = ["John": 85, "Emma": 92, "Michael": 78, "Sophia": 95]
for (name, score) in studentScores {
print("\(name) scored \(score) points")
}
Output:
John scored 85 points
Emma scored 92 points
Michael scored 78 points
Sophia scored 95 points
Strings
You can iterate through the characters in a string:
let greeting = "Hello"
for character in greeting {
print(character)
}
Output:
H
e
l
l
o
Using Enumerated()
Sometimes you need to know the index of each element while iterating. The enumerated()
method provides both the index and the value:
let planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter"]
for (index, planet) in planets.enumerated() {
print("Planet \(index + 1): \(planet)")
}
Output:
Planet 1: Mercury
Planet 2: Venus
Planet 3: Earth
Planet 4: Mars
Planet 5: Jupiter
Conditional Iterations
Using where Clause
You can add a where
clause to filter iterations:
// Print only even numbers
for number in 1...10 where number % 2 == 0 {
print(number)
}
Output:
2
4
6
8
10
Stride Function
If you want to iterate with a specific step size, you can use the stride(from:to:by:)
function:
// Count from 0 to 10 by 2
for i in stride(from: 0, to: 11, by: 2) {
print(i)
}
Output:
0
2
4
6
8
10
Note that stride(from:to:by:)
doesn't include the upper bound. If you want to include the upper bound, use stride(from:through:by:)
:
// Count down from 10 to 1 with a step of -2
for i in stride(from: 10, through: 1, by: -2) {
print(i)
}
Output:
10
8
6
4
2
Ignoring the Loop Variable
If you don't need the current value in the loop iteration, you can use the underscore (_
):
// Print "Hello!" 5 times
for _ in 1...5 {
print("Hello!")
}
Output:
Hello!
Hello!
Hello!
Hello!
Hello!
Practical Examples
Example 1: Calculating Factorial
func factorial(of number: Int) -> Int {
var result = 1
for i in 1...number {
result *= i
}
return result
}
let number = 5
let factorialResult = factorial(of: number)
print("Factorial of \(number) is \(factorialResult)")
Output:
Factorial of 5 is 120
Example 2: Building a Multiplication Table
func multiplicationTable(for number: Int, upto range: Int) {
print("Multiplication table for \(number):")
for i in 1...range {
print("\(number) × \(i) = \(number * i)")
}
}
multiplicationTable(for: 7, upto: 5)
Output:
Multiplication table for 7:
7 × 1 = 7
7 × 2 = 14
7 × 3 = 21
7 × 4 = 28
7 × 5 = 35
Example 3: Finding Prime Numbers
func isPrime(_ number: Int) -> Bool {
guard number > 1 else { return false }
// Check if number is divisible by any integer from 2 to sqrt(number)
for divisor in 2..<Int(Double(number).squareRoot()) + 1 {
if number % divisor == 0 {
return false
}
}
return true
}
print("Prime numbers between 1 and 20:")
for number in 1...20 {
if isPrime(number) {
print(number, terminator: " ")
}
}
Output:
Prime numbers between 1 and 20:
2 3 5 7 11 13 17 19
Summary
The for loop in Swift provides a powerful and flexible way to iterate through ranges and collections. Here's what we've covered:
- Basic for-in loop syntax
- Iterating through ranges using closed range (
...
), half-open range (..<
), and one-sided ranges - Iterating through collections like arrays, dictionaries, and strings
- Using
enumerated()
to access both index and value - Filtering iterations with the
where
clause - Using
stride()
to iterate with specific steps - Ignoring loop variables with underscore (
_
) - Real-world applications and examples
For loops are a fundamental part of Swift programming and are essential for tasks ranging from simple repetition to complex data processing.
Exercises
- Write a for loop that prints the first 10 Fibonacci numbers.
- Create a function that uses a for loop to reverse a string.
- Write a program that finds all numbers between 1 and 100 that are divisible by both 3 and 5.
- Use a for loop to convert an array of strings to an array of their lengths.
- Implement a function that uses a for loop to find the smallest and largest values in an array of integers.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)