Swift Functions Overloading

In Swift, we can define multiple functions with the same name, but with different parameters or return types. This is called function overloading. Function overloading helps us to write cleaner and more readable code by providing a way to give multiple meanings to a single function name.

Function Overloading

Function overloading is a technique in which multiple functions can have the same name but with different parameters or return types. When a function is called, the compiler chooses the correct function based on the number, types, and order of the arguments passed.

For example, let's define two functions with the same name but different parameters:

1func sum(_ a: Int, _ b: Int) -> Int { 2 return a + b 3} 4 5func sum(_ a: Double, _ b: Double) -> Double { 6 return a + b 7}

Here, we have defined two functions named sum with different parameter types. The first sum function takes two Int parameters and returns an Int, while the second sum function takes two Double parameters and returns a Double.

Now, we can call the sum function with different argument types:

1let intSum = sum(2, 3) // Returns 5 2let doubleSum = sum(2.5, 3.5) // Returns 6.0

Here, the compiler knows which sum function to call based on the types of the arguments.

Function Overloading with Optional Parameters

Function overloading also works with optional parameters. We can define multiple functions with the same name and different optional parameters.

For example, let's define two functions with the same name and an optional parameter:

1func greet(_ name: String) { 2 print("Hello, \(name)!") 3} 4 5func greet(_ name: String, withMessage message: String = "Welcome") { 6 print("\(message), \(name)!") 7}

Here, we have defined two functions named greet. The first greet function takes one parameter, while the second greet function takes two parameters, where the second parameter has a default value of "Welcome".

Now, we can call the greet function with or without the second parameter:

1greet("William") // Prints "Hello, William!" 2greet("Jane", withMessage: "Good morning") // Prints "Good morning, Jane!"

Here, if we call the greet function with one parameter, it will call the first greet function. If we call the greet function with two parameters, it will call the second greet function.