Overloading
Did you notice how you used the same function name for several different functions in the previous examples?
func printMultipleOf(multiplier: Int, andValue: Int) func printMultipleOf(multiplier: Int, and value: Int) func printMultipleOf( multiplier: Int, and value: Int) func printMultipleOf( multiplier: Int, _ value: Int)
This technique is called overloading and allows you to define similar functions using a single name.
However, the compiler must still be able to tell the difference between these functions. Whenever you call a function, it should always be clear which function you’re calling. This is usually achieved through a difference in the parameter list:
- A different number of parameters.
- Different parameter types.
- Different external parameter names, such as the case with printMultipleOf. You can also overload a function name based on a different return type, like so:
func getValue() -> Int { return 31;
}
func getValue() -> String { return "Matt Galloway"
}
Here, there are two functions called getValue(), which return different types. One an Int and the other a String.
Using these is a little more complicated. Consider the following:
let value = getValue()
How does Swift know which getValue() to call? The answer is, it doesn’t. And it will print the following error:
error: ambiguous use of 'getValue()'
There’s no way of knowing which one to call. It’s a chicken and egg situation. It’s unknown what type value is, so Swift doesn’t know which getValue() to call or what the return type of getValue() should be.
To fix this, you can declare what type you want value to be, like so:
let valueInt: Int = getValue()
let valueString: String = getValue()
This will correctly call the Int version of getValue() in the first instance, and the
String version of getValue() in the second instance.
It’s worth noting that overloading should be taken with a pinch of salt. It’s recommended to only use overloading for functions that are related and similar in behavior. Otherwise, it can cause confusion, especially when the return type is overloaded as above.