What if you could write a piece of code once and use it everywhere without repeating yourself?
Why Adding methods in Swift? - Purpose & Use Cases
Imagine you have a simple calculator app, and you want to add the ability to multiply numbers. Without methods, you'd have to write the multiplication code every time you need it, scattered all over your program.
Writing the same multiplication steps repeatedly is slow and easy to mess up. If you want to change how multiplication works, you must find and fix every spot manually, which is frustrating and error-prone.
Adding methods lets you bundle the multiplication steps into one reusable block. You write it once, then call it whenever you want. This keeps your code clean, easy to update, and less buggy.
let result = a * b // repeated everywhere you need multiplication
func multiply(_ x: Int, _ y: Int) -> Int {
return x * y
}
let result = multiply(a, b)It makes your code organized and lets you reuse actions easily, saving time and avoiding mistakes.
Think of a coffee machine: instead of pressing separate buttons for each step, you press one button that runs the whole coffee-making process. Methods are like that button for your code.
Methods group code into reusable actions.
They reduce repetition and errors.
They make programs easier to read and maintain.