DEV Community

Gamya
Gamya

Posted on

Swift For Loops

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)")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Currently watching: Naruto
Currently watching: One Piece
Currently watching: Demon Slayer
Currently watching: Attack on Titan
Enter fullscreen mode Exit fullscreen mode

Let's break down what's happening:

  • for show in animeShows β€” Swift takes each item from the array one by one and puts it into show
  • show is 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 (show here) is completely up to you. You could write for s in animeShows or even for 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)")
}
Enter fullscreen mode Exit fullscreen mode

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 12 = 60
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

..< Half-Open Range β€” "up to but NOT including"

for i in 1..<5 {
    print(i) // prints 1, 2, 3, 4
}
Enter fullscreen mode Exit fullscreen mode

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.count safely 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])")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Member 1: Naruto
Member 2: Sasuke
Member 3: Sakura
Member 4: Kakashi
Enter fullscreen mode Exit fullscreen mode

↔️ 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
Enter fullscreen mode Exit fullscreen mode

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()
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

Goku is powering up!!!!!
Enter fullscreen mode Exit fullscreen mode

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...5 but never use i inside 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! πŸƒ")
Enter fullscreen mode Exit fullscreen mode

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! πŸƒ
Enter fullscreen mode Exit fullscreen mode

🌟 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...] or array[...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)

Collapse
 
junhao profile image
Jun Hao

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! πŸš€πŸ‘πŸ’–

Collapse
 
gamya_m profile image
Gamya

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! πŸš€πŸŒ·

Collapse
 
junhao profile image
Jun Hao

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🌸🌸🌸

Thread Thread
 
gamya_m profile image
Gamya

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! πŸš€πŸŒΈ