When you’re writing code, there are often tasks that need to be repeated multiple times. Instead of writing the same code over and over again, Swift gives us loops—powerful constructs that allow us to repeat a set of instructions until a condition is met. Whether you’re iterating through arrays, counting numbers, or performing repetitive tasks, loops make your code cleaner, shorter, and easier to manage.
In this article, we’ll explore the different types of loops in Swift, how to use them efficiently, and provide practical examples for each. By the end, you’ll have a solid understanding of how to control the flow of repetition in your Swift programs.
What Are Loops?
A loop allows you to execute a block of code multiple times, either for a specific number of times or until a condition is satisfied. In Swift, there are several types of loops, each suited for different tasks:
- For loops: Used when you know how many times the code should run.
- While loops: Used when you don’t know how many times the code should run but want it to continue until a certain condition is met.
- Repeat-while loops: A variation of the while loop that guarantees the code runs at least once.
Let’s dive into each type of loop, starting with the most common one: the for loop.
For Loop in Swift
The for loop in Swift is one of the most commonly used loops. It allows you to iterate over collections (like arrays or ranges) and execute code for each item in the collection.
Here’s the basic syntax of a for loop:
for item in collection {
// Code to execute for each item
}
Example 1: Iterating Over an Array
Let’s start with a simple example where we iterate over an array of strings:
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
print("I love \(fruit)")
}
In this example, the loop runs three times, once for each fruit in the array. The result will be:
I love Apple
I love Banana
I love Cherry
Example 2: Using a Range in a For Loop
You can also use a range in a for loop to repeat code a specific number of times:
for number in 1...5 {
print("Number: \(number)")
}
Here, the loop will run 5 times, with number
taking values from 1 to 5. The result will be:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Example 3: Looping with Step Values
If you want to skip certain values or loop over a range with a step size, you can use the stride()
function:
for number in stride(from: 0, through: 10, by: 2) {
print(number)
}
This loop will print every second number from 0 to 10, resulting in:
0
2
4
6
8
10
While Loop in Swift
A while loop keeps running a block of code as long as a specified condition is true. This is particularly useful when you don’t know exactly how many times the loop should run ahead of time.
Here’s the basic syntax of a while loop:
while condition {
// Code to execute while the condition is true
}
Example 4: Basic While Loop
Let’s use a while loop to count down from 5:
var count = 5
while count > 0 {
print("Countdown: \(count)")
count -= 1
}
This loop will continue running as long as count
is greater than 0. Each time, it decreases count
by 1, and the result will be:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Once count
reaches 0, the condition count > 0
becomes false, and the loop stops.
Repeat-While Loop
The repeat-while loop is a variation of the while loop that executes the block of code at least once, even if the condition is false from the start. This is useful when you need to ensure the code runs at least one time before checking the condition.
Here’s the basic syntax:
repeat {
// Code to execute
} while condition
Example 5: Basic Repeat-While Loop
Let’s use a repeat-while loop to ensure the code runs at least once:
var number = 0
repeat {
print("Current number is \(number)")
number += 1
} while number < 3
The loop will print:
Current number is 0
Current number is 1
Current number is 2
Even though number
starts at 0, the code inside the loop runs once before checking the condition. The loop stops after number
reaches 3.
Controlling Loop Execution with Break and Continue
Swift offers two useful control statements for loops: break and continue. These allow you to control how and when the loop should stop or skip over iterations.
Break
The break statement exits the loop entirely, no matter how many iterations are left. This is useful when you want to stop the loop based on a specific condition.
for number in 1...10 {
if number == 5 {
print("Found 5, exiting the loop.")
break
}
print("Number: \(number)")
}
In this example, the loop will stop as soon as it reaches 5:
Number: 1
Number: 2
Number: 3
Number: 4
Found 5, exiting the loop.
Continue
The continue statement skips the current iteration and moves to the next one. This is useful when you want to bypass certain iterations without stopping the entire loop.
for number in 1...5 {
if number == 3 {
continue
}
print("Number: \(number)")
}
This loop will skip printing 3
, resulting in:
Number: 1
Number: 2
Number: 4
Number: 5
Looping Through Dictionaries
In Swift, you can also loop through dictionaries. When you loop through a dictionary, each iteration gives you both the key and the value.
Example 6: Looping Through a Dictionary
let capitals = ["France": "Paris", "Japan": "Tokyo", "USA": "Washington, D.C."]
for (country, capital) in capitals {
print("The capital of \(country) is \(capital).")
}
This will print:
The capital of France is Paris.
The capital of Japan is Tokyo.
The capital of USA is Washington, D.C.
Nested Loops
Sometimes, you may need to place one loop inside another, creating a nested loop. This is useful when working with multidimensional arrays or performing tasks like generating multiplication tables.
Example 7: Nested For Loops
Here’s a simple example of a nested for loop that prints a multiplication table:
for i in 1...3 {
for j in 1...3 {
print("\(i) * \(j) = \(i * j)")
}
}
This loop will output:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
Looping Through Collections with Indexes
Sometimes, you might need both the index and the value while looping through a collection. In Swift, you can use the enumerated()
method to achieve this.
Example 8: Using Indexes with Enumerated
let names = ["Alice", "Bob", "Charlie"]
for (index, name) in names.enumerated() {
print("Index \(index): \(name)")
}
This loop will print both the index and the value:
Index 0: Alice
Index 1: Bob
Index 2: Charlie
Infinite Loops
An infinite loop occurs when the loop’s condition is always true, causing the loop to run forever. Infinite loops are often used in situations where the program needs to wait for a specific event, like user input, or in games that require constant updates.
However, you should be careful with infinite loops, as they can cause your program to freeze or crash if not handled properly.
Example 9: Infinite Loop (Use with Caution!)
while true {
print("This will print forever!")
break // Always include a way to exit the loop!
}
In this example, the break
statement prevents the loop from running indefinitely.
Real-World Example: Password Validation
Let’s use what we’ve learned to build a simple password validation system that prompts the user to enter a password until the correct one is entered:
var password = "swift123"
var input: String?
repeat
{
print("Enter your password:")
input = readLine() // Assume input is collected
} while input != password
print("Access granted!")
In this example, the repeat-while loop ensures the user is prompted until the correct password is entered.
Conclusion
Loops are one of the most essential tools in programming, allowing you to efficiently handle repetitive tasks. In Swift, loops come in several flavors—for loops, while loops, and repeat-while loops—each designed for specific use cases. Understanding how to use loops effectively will greatly improve your ability to solve problems in Swift.
In this article, we covered:
- For loops for iterating over collections and ranges.
- While loops for executing code until a condition is no longer met.
- Repeat-while loops to ensure code runs at least once.
- Break and continue to control loop execution.
- Nested loops and looping through dictionaries for more complex tasks.
In the next article, we’ll explore functions in Swift—how to write reusable blocks of code that make your programs more modular and maintainable.
Happy coding!