Imagine you've written a really useful piece of code and now you need it in 10 different places in your app. Do you copy and paste it 10 times? What if you need to change it later โ would you remember to update all 10 copies?
That's exactly the problem functions solve. Write it once, use it everywhere. ๐ง
๐ง What Is a Function?
A function is a named chunk of code that you can run whenever and wherever you need it. Instead of repeating the same code over and over, you wrap it up in a function, give it a name, and just call that name whenever you need it.
Here's a simple example โ a welcome message for an app:
func showWelcome() {
print("Welcome to the Ninja Academy! ๐")
print("Track your training progress here.")
print("Set your goals and crush them!")
print("Let's get started!")
}
Breaking it down:
-
funcโ tells Swift we're creating a function -
showWelcomeโ the name we give it (make it descriptive!) -
{ }โ the function body โ everything inside runs when the function is called
Now whenever we need that welcome message โ we just call it:
showWelcome()
That's called the call site โ the place where we call the function. And we can call it as many times as we want, anywhere in our code! โ
๐ก Why Functions Matter
Here's the honest truth about why functions are so important โ told through a famous story from programming history:
Dennis Ritchie, the creator of the C programming language, encouraged developers to use lots of small functions by telling everyone that function calls were really cheap. Everyone started writing modular code. Years later they found out function calls were actually expensive โ but by then nobody cared, because the code was so much cleaner and easier to maintain! ๐
The lesson? Even when functions had a performance cost โ developers preferred them because of how much they improved code quality. Today that cost is essentially gone, and functions are one of the most fundamental tools in any language.
โ๏ธ Functions with Parameters
Functions become really powerful when you can pass data into them to customize how they work. You've already been using this without realising it:
// isMultiple(of:) is a function that takes a parameter!
number.isMultiple(of: 2)
// random(in:) is a function that takes a parameter!
Int.random(in: 1...20)
We can create our own functions that work the same way. Here's a times table printer:
func printTimesTables(number: Int) {
for i in 1...12 {
print("\(i) x \(number) = \(i * number)")
}
}
printTimesTables(number: 5)
Output:
1 x 5 = 5
2 x 5 = 10
3 x 5 = 15
...
12 x 5 = 60
The number: Int inside the parentheses is called a parameter โ it's a placeholder that gets filled in when the function is called. When we write printTimesTables(number: 5) โ the 5 is the argument โ the actual value we're passing in.
๐ก Parameter vs Argument โ don't stress about this distinction too much! A parameter is the placeholder in the function definition, an argument is the actual value you pass when calling it. Easy way to remember: Parameter = Placeholder, Argument = Actual value. ๐
๐ฆ Multiple Parameters
Functions can take more than one parameter:
func printTimesTables(number: Int, end: Int) {
for i in 1...end {
print("\(i) x \(number) = \(i * number)")
}
}
printTimesTables(number: 5, end: 20)
Notice how we name each parameter when calling the function โ number: 5, end: 20. This is one of Swift's nicest features โ you always know exactly what each value means just by reading the call site!
Compare these two:
printTimesTables(number: 5, end: 20) // โ
crystal clear
printTimesTables(5, 20) // โ which is which?
Six months from now you'll thank yourself for using named parameters! ๐ธ
โ ๏ธ Important: Parameters must always be passed in the same order they were defined. This won't work:
printTimesTables(end: 20, number: 5) // โ wrong order!
๐๏ธ When Should You Create a Function?
There are three main situations where functions are the right tool:
1๏ธโฃ When You Need the Same Code in Multiple Places
func showBattleIntro() {
print("โ๏ธ Battle starting!")
print("Prepare your jutsu!")
print("May the best ninja win!")
}
// Use it at the start of every battle
showBattleIntro() // round 1
showBattleIntro() // round 2
showBattleIntro() // round 3
If you ever want to change the intro โ change it once in the function and every battle automatically gets the update! No hunting through your code for every copy. โ
2๏ธโฃ When You Want to Break Up Long Code
Imagine one massive function doing 200 things โ impossible to read! Breaking it into smaller focused functions makes everything cleaner:
func prepareForBattle() { }
func executeBattle() { }
func showBattleResults() { }
Each function has one clear job โ easy to read, easy to fix, easy to update. ๐ธ
3๏ธโฃ Function Composition โ Building Big from Small
Swift lets you call functions from inside other functions โ building complex behaviour from simple pieces, like Lego bricks! ๐งฑ
func greetNinja(name: String) {
print("Welcome \(name)!")
}
func startTraining(name: String, jutsu: String) {
greetNinja(name: name) // calling another function inside!
print("Today we practice \(jutsu).")
}
startTraining(name: "Naruto", jutsu: "Rasengan")
Output:
Welcome Naruto!
Today we practice Rasengan.
โ ๏ธ How Many Parameters Is Too Many?
There's no hard rule โ but when a function starts taking 6 or more parameters it's worth stopping and asking:
- Does it really need all of them?
- Could it be split into smaller functions?
- Should some of those parameters be grouped together?
In programming this is called a "code smell" โ not that the code is wrong, but something about it hints that the structure might need rethinking. A function with too many parameters is often trying to do too much at once! ๐ง
๐งฉ Putting It All Together
Here's a mini ninja training system using everything we covered:
func showAcademyWelcome() {
print("๐ Welcome to the Hidden Leaf Academy!")
print("Train hard and become the best ninja!")
}
func printTrainingSchedule(ninja: String, jutsu: String, days: Int) {
print("\n๐ Training Schedule for \(ninja):")
for day in 1...days {
print("Day \(day): Practice \(jutsu)")
}
}
func announceGraduation(ninja: String, rank: String) {
print("\n๐ Congratulations \(ninja)!")
print("You have achieved the rank of \(rank)!")
}
// Using all three functions together
showAcademyWelcome()
printTrainingSchedule(ninja: "Naruto", jutsu: "Shadow Clone Jutsu", days: 3)
announceGraduation(ninja: "Naruto", rank: "Genin")
Output:
๐ Welcome to the Hidden Leaf Academy!
Train hard and become the best ninja!
๐ Training Schedule for Naruto:
Day 1: Practice Shadow Clone Jutsu
Day 2: Practice Shadow Clone Jutsu
Day 3: Practice Shadow Clone Jutsu
๐ Congratulations Naruto!
You have achieved the rank of Genin!
๐ Wrap Up
Functions are one of the most important tools in Swift โ and in programming in general:
-
func name() { }โ defines a function -
name()โ calls a function - Parameters let you customize how a function works
- Arguments are the actual values you pass when calling
- Always write parameter names when calling โ it makes code self documenting
- Create functions when you need the same code in multiple places
- Create functions to break up long complex code into readable pieces
- Watch out for functions with too many parameters โ that's a code smell!
And remember โ any data you create inside a function is automatically destroyed when the function finishes. It stays contained! ๐
Next up we'll look at return values โ getting data back out of functions. See you there! ๐
Top comments (6)
My DEAR GamYa
๐ Excellent article! I really enjoyed how you broke down Swift functions into simple, easy-to-understand concepts while still covering important development best practices. ๐ง The explanations of parameters, arguments, function composition, and code organization were especially valuable because they help developers understand not just how functions work, but why they are such a fundamental part of writing maintainable code. ๐ The real-world examples and ninja-themed demonstrations made the learning experience engaging and memorable, which is something many technical tutorials struggle to achieve. ๐ก I also appreciated the discussion about code smells and keeping functions focused on a single responsibility, as these habits can make a huge difference as projects grow in size and complexity. ๐ Thanks for creating such a well-structured and beginner-friendly guideโit's a great resource for anyone learning Swift and building a strong foundation in iOS development!
Thank you so much! ๐ฅน๐ Really glad the ninja examples helped the concepts stick โ functions felt like such a big topic to cover but breaking it into pieces with the parameter/argument distinction made it click for me too while writing it! Thanks for always taking the time to leave such thoughtful comments! ๐ธ๐
I am an assembly and C++ developer, but I would like to learn Swift very much!!โฅ๏ธ
That's awesome! ๐ Coming from Assembly and C++ you'll probably find a lot of Swift concepts feel really intuitive โ especially the lower-level stuff like memory and types. Swift is a great next step, and honestly your background will probably make some of the "why" behind certain design choices click faster than for total beginners! Good luck, and let me know if you have any questions along the way! ๐
I truly believe that I can learn a lot from you.๐
Aww that means a lot, thank you! ๐ Honestly with your Assembly and C++ background I think it'll go both ways โ looking forward to following your Swift journey! ๐ธ