Swift Function Overloading
When two are more functions have same name but different arguments then they are known as overloaded functions and this process in known as function overloading.
Need of Function Overloading
Let's suppose a condition. You have to develop a shooter game where the player can attack its enemies using a knife, a grenade and a gun. Let's see how your solution for the attack functionality might be defining the actions into functions:
You can see that the above program is confusing for the compiler and you will get a compile time error while executing the program in Swift as 'attack()' previously declared here. However, another solution might be defining different function names for the particular functionality as:
In the above example, you have used struct to create the physical objects like Knife, Grenade, and Gun. There is also a problem with the above example that we have to remember the different function?s name to call that particular action attack. To overcome with this problem, function overloading is used where the name of the different functions are same but passed parameters are different.
Same example with Function Overloading
Attacking with Knife Attacking with Grenade Attacking with Gun
In the above program, three different functions are created with a same name ?attack?. It takes different parameter types and by this way, we call this function in different conditions.
Function Overloading with Different Parameter types
Welcome to Special 26
In the above program, both functions have same name output() and same number of parameter but the different parameter type. The first output() function takes a string as a parameter, and the second output() function takes an integer as a parameter.