Computers are extraordinary at one thing humans are terrible at — doing the same task over and over again, perfectly, without getting bored or making mistakes. Loops are what make that possible, and in Swift they're clean, powerful, and surprisingly fun to write. 🚀
🔁 Looping Over an Array
The most common use of a for loop is going through every item in an array and doing something with each one:
let animeShows = ["Naruto", "One Piece", "Demon Slayer", "Attack on Titan"]
for show in animeShows {
print("Currently watching: \(show)")
}
Output:
Currently watching: Naruto
Currently watching: One Piece
Currently watching: Demon Slayer
Currently watching: Attack on Titan
Let's break down what's happening:
-
for show in animeShows— Swift takes each item from the array one by one and puts it intoshow -
showis called the loop variable — it only exists inside the loop and changes every iteration - The code inside
{ }is called the loop body — it runs once for every item - One full run through the loop body is called a loop iteration
💡 The loop variable name (
showhere) is completely up to you. You could writefor s in animeShowsor evenfor rubberChicken in animeShows— Swift doesn't care. Pick something readable!
The same syntax works for sets and dictionaries too — not just arrays. 🌸
🔢 Looping Over a Range of Numbers
You don't always need an array to loop. Swift lets you loop over a range of numbers directly:
for i in 1...12 {
print("5 x \(i) = \(5 * i)")
}
Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 12 = 60
The 1...12 is a closed range — it includes both 1 and 12 and everything in between. Think of it as "1 through 12".
The loop variable i is a common convention for a counting number. If you need a second counter you'd use j, and a third would be k.
📐 Two Types of Ranges
Swift gives us two range operators and they behave slightly differently:
... Closed Range — "up to and including"
for i in 1...5 {
print(i) // prints 1, 2, 3, 4, 5
}
..< Half-Open Range — "up to but NOT including"
for i in 1..<5 {
print(i) // prints 1, 2, 3, 4
}
A helpful way to remember:
-
1...5→ "1 through 5" → includes 5 -
1..<5→ "1 up to 5" → excludes 5
| Operator | Name | Includes end value? | Example result |
|---|---|---|---|
... |
Closed range | ✅ Yes |
1...3 → 1, 2, 3 |
..< |
Half-open range | ❌ No |
1..<3 → 1, 2 |
💡 Half-open ranges are perfect for arrays since arrays start at index
0. If an array has 4 items,0..<array.countsafely covers all indexes without going out of bounds.
let squad = ["Naruto", "Sasuke", "Sakura", "Kakashi"]
for i in 0..<squad.count {
print("Member \(i + 1): \(squad[i])")
}
Output:
Member 1: Naruto
Member 2: Sasuke
Member 3: Sakura
Member 4: Kakashi
↔️ One-Sided Ranges
Sometimes you want "everything from index 1 to the end" or "everything up to index 2" without specifying both sides. Swift handles this with one-sided ranges:
let characters = ["Luffy", "Zoro", "Nami", "Usopp", "Sanji"]
print(characters[2...]) // ["Nami", "Usopp", "Sanji"] — from index 2 to end
print(characters[...2]) // ["Luffy", "Zoro", "Nami"] — from start to index 2
print(characters[1..<3]) // ["Zoro", "Nami"] — index 1 up to but not including 3
This is really handy when you don't know exactly how long an array will be but you know where you want to start or stop reading from.
🪆 Nested Loops
You can put a loop inside another loop — this is called a nested loop. A classic use case is building a times table:
for i in 1...3 {
print("The \(i) times table:")
for j in 1...3 {
print(" \(j) x \(i) = \(j * i)")
}
print()
}
Output:
The 1 times table:
1 x 1 = 1
2 x 1 = 2
3 x 1 = 3
The 2 times table:
1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
The 3 times table:
1 x 3 = 3
2 x 3 = 6
3 x 3 = 9
The outer loop runs 3 times, and for each of those the inner loop also runs 3 times — giving us 9 total iterations. print() with nothing inside just adds a blank line to make the output easier to read.
🔳 The Underscore — When You Don't Need the Loop Variable
Sometimes you want to repeat something a set number of times but you don't actually need to use the loop variable inside the body. In that case, replace it with an underscore _:
var powerUpMessage = "Goku is powering up"
for _ in 1...5 {
powerUpMessage += "!"
}
print(powerUpMessage)
Output:
Goku is powering up!!!!!
The underscore tells Swift "I know there's a loop variable here, but I don't need it". This also signals to anyone reading your code that the variable is intentionally unused — no confusion, no guessing. 🧠
⚠️ If you write
for i in 1...5but never useiinside the loop, Swift will actually warn you and suggest replacing it with_. It's Swift's way of keeping your code clean!
🧩 Putting It All Together
Here's a mini training simulator combining everything:
let jutsuList = ["Rasengan", "Shadow Clone", "Sage Mode"]
var totalPracticed = 0
print("=== Training Session ===")
for jutsu in jutsuList {
for _ in 1...3 {
totalPracticed += 1
}
print("Practiced \(jutsu) 3 times ✅")
}
print()
print("Total practice rounds: \(totalPracticed)")
// Print a countdown
print()
print("Mission starts in:")
for i in (1...3).reversed() {
print("\(i)...")
}
print("Go! 🏃")
Output:
=== Training Session ===
Practiced Rasengan 3 times ✅
Practiced Shadow Clone 3 times ✅
Practiced Sage Mode 3 times ✅
Total practice rounds: 9
Mission starts in:
3...
2...
1...
Go! 🏃
🌟 Wrap Up
For loops are one of the most powerful and frequently used tools in Swift. Here's everything to remember:
-
for item in collection— loops over every item in an array, set, or dictionary -
for i in 1...5— closed range, includes both ends (1 through 5) -
for i in 1..<5— half-open range, excludes the end (1 up to 5) - One-sided ranges like
array[2...]orarray[...2]let you slice collections cleanly - Nested loops run the inner loop fully for every iteration of the outer loop
- Use
_when you don't need the loop variable — it keeps your code clean and intentional
Loops make the impossible possible — imagine writing 1000 print statements by hand versus one loop. Once you're comfortable with these, you'll use them everywhere. 💪
Top comments (0)