DEV Community

Gamya
Gamya

Posted on

Swift Functions โ€” Write Once, Use Everywhere ๐Ÿ”ง

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

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

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

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

Output:

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

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

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

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

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

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

Output:

Welcome Naruto!
Today we practice Rasengan.
Enter fullscreen mode Exit fullscreen mode

โš ๏ธ 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")
Enter fullscreen mode Exit fullscreen mode

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

๐ŸŒŸ 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)

Collapse
 
junhao profile image
Jun Hao

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!

Collapse
 
gamya_m profile image
Gamya

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! ๐ŸŒธ๐Ÿš€

Collapse
 
technogamerz profile image
The Lazy Girl (โ โ—• โ แด— โ โ—• โ โœฟโ ) • Edited

I am an assembly and C++ developer, but I would like to learn Swift very much!!โ™ฅ๏ธ

Collapse
 
gamya_m profile image
Gamya

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! ๐Ÿš€

Collapse
 
technogamerz profile image
The Lazy Girl (โ โ—• โ แด— โ โ—• โ โœฟโ )

I truly believe that I can learn a lot from you.๐Ÿ˜Š

Thread Thread
 
gamya_m profile image
Gamya

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! ๐ŸŒธ