[Swift Apple ] 8. Repeating with For Loops



🔁 8. Repeating with For Loops


Hello again! 😊

In today’s lesson, we’ll learn how to make Swift do the same thing over and over again — just like a robot!

This is called a loop, and we’re going to use a special one called the for loop.


Ready to repeat some fun? Let’s go! 🔄🚀



🔁 What Is a Loop?


A loop tells the computer:


“Do this action many times!”


Instead of writing the same line again and again,

we can tell Swift to repeat it for us.

That’s what the for loop does!



🎯 For Loop: Do Something Over and Over


Here’s a simple example.

Let’s say we want to print the word “Hello” 5 times:

for _ in 1...5 {
    print("Hello")
}





Output:

Hello  
Hello  
Hello  
Hello  
Hello

Cool, right? Just one line of code tells Swift to do it five times!





🧪 Practice: Count from 1 to 10


Now let’s build something fun:

A program that counts from 1 to 10 and prints each number!

for number in 1...10 {
    print(number)
}





Output:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10





You can also count backward like this:

for number in (1...10).reversed() {
    print(number)
}





Output:

10  
9  
8  
7  
6  
5  
4  
3  
2  
1






💡 Try This Challenge!


Can you print “🎉” 7 times using a loop?


Hint:

for _ in 1...7 {
    print("🎉")
}

That’s how loops can even help you with fun patterns and emojis!





✨ Wrapping Up


Today, we learned how to repeat actions using for loops:

  • Loops tell the computer to do something multiple times

  • for number in 1...10 lets us count up

  • for _ in 1...5 repeats without needing the number

  • You can even use emojis and backward loops!



댓글 쓰기