🎁 10. Functions Are Magic Boxes!
This version is friendly, beginner-level, and great for kids or anyone new to Swift programming.
🎁 10. Functions Are Magic Boxes!
Hello again! 😊 Today we’re going to learn about something super useful in Swift:
Functions!
A function is like a magic box:
you can put code inside and give it a name,
and then reuse it anytime with just one line!
Sounds like magic, right? ✨
📦 A Function Is a Named Action!
Instead of writing the same code again and again,
you can save it in a function and use it whenever you want.
For example, if you often say hello with this code:
print("Hello! Nice to meet you 😊")
You can turn it into a function like this:
func sayHello() {
print("Hello! Nice to meet you 😊")
}
Now every time you write sayHello(),
Swift will run the greeting for you!
🧪 Practice: Make a Greeting Function
Let’s create a function that greets someone by name.
func greet(name: String) {
print("Hello, \(name)! Have a great day ☀️")
}
Now call the function like this:
greet(name: "Jiyoo")
greet(name: "Minjun")
Output:
Hello, Jiyoo! Have a great day ☀️
Hello, Minjun! Have a great day ☀️
💡 name: String means we’re giving the function a name to use,
and \(name) adds that name into the sentence — this is called string interpolation!
🎯 Why Use Functions?
Functions help make your code:
-
✅ Reusable – use it again and again
-
✅ Organized – your code looks cleaner
-
✅ Easy to update – change one function, and everything updates!
💡 Challenge: Make a “Good Night” Function
Let’s try making your own function now!
When you give a name, it should say:
“Good night, ___! Sweet dreams 🌙”
Here’s a hint:
func sayGoodNight(name: String) {
print("Good night, \(name)! Sweet dreams 🌙")
}
Give it a try with your own name!
✨ Wrapping Up
Today, you learned that:
-
A function is like a magic box with code inside
-
You create one with func
-
You call the function later to make it run
Functions help your programs become smarter, shorter, and more fun!
댓글 쓰기