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 (4)
Hello,
π·π·π·MY DEAR GAMYAπ·π·π·
I am glad to upload my comments your post
π©βπ»β¨ This is an excellent explanation of Swift loopsβclear, engaging, and packed with practical examples.
The progression from basic array iteration to ranges, nested loops, and one-sided ranges makes the learning process feel natural and easy to follow.
I especially like how real-world examples using anime characters and training scenarios keep the content interesting while reinforcing important concepts.
πΈ The breakdowns of loop variables, iterations, and range operators are beginner friendly without sacrificing accuracy.
π©βπ« The section on using
_for unused loop variables is a great touch because it teaches clean coding habits early.π‘ The code samples are simple enough to understand at a glance while still demonstrating real Swift patterns developers use every day. π©βπ» The visual comparisons between closed and half-open ranges make a common source of confusion much easier to grasp.
π· Overall, this is a well-structured, informative, and enjoyable guide that helps readers build confidence with one of Swift's most essential programming tools. Great work! πππ
Jun Hao you always leave the most thoughtful comments β thank you so much! πΈπ The underscore for unused loop variables is one of those small things that makes such a big difference in writing clean Swift, so really glad that stood out! And yes the anime examples make everything so much more fun to write too π Always look forward to seeing your thoughts β see you in the next one! ππ·
My dear Gamyaπππ
thank you so much
I will always watch everything you post and will always be a supporter.
I think I am a top reader of your articles
I always expect you to write good articles.
Looking forward to always being happy in your business and life.
from your close friendπΈπΈπΈπΈ
Best RegardsπΈπΈπΈ
This is honestly the sweetest thingβthank you so much Jun Hao! π Having a loyal reader like you makes this whole journey so much more meaningful and enjoyable. Your consistent support and kind words genuinely keep me motivated to keep writing and improving! More great articles are on the way β this is just the beginning! ππΈ