Home » Swift Function Overloading

Swift Function Overloading

by Online Tutorials Library

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:

Example:

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

Output:

Attacking with Knife  Attacking with Grenade  Attacking with Gun  

Program explanation

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.

  • The call attack(with: Gun()) triggers the statement inside the function func attack(with weapon:Gun).
  • The call attack(with: Grenade()) triggers the statement inside the function func attack(with weapon:Grenade).
  • The call attack(with: Knife()) statement inside the function func attack(with weapon:Knife).

Function Overloading with Different Parameter types

Example:

Output:

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.

  • The call to output(x: “Special”) triggers the statement inside the function func output(x:String).
  • And the call to output(x: 26) triggers the statement inside the function func output(x:Int).

Next TopicSwift Arrays

You may also like