- Mastering macOS Programming
- Stuart Grimshaw
- 136字
- 2021-07-02 22:54:32
Function overloading
If a function could reasonably be expected, from its name, to apply to different data types, which is certainly the case with our triple function, then we can overload it, meaning that we use the same symbol, but provide different argument types.
We could expand our triple function to apply to Double values, by providing this new function signature:
func triple(_ a: Double) -> Double
{
return a * 3.0
}
If we should decide that triple("la") makes perfect sense in the context of our program, we can again provide an additional implementation with the appropriate signature:
func triple(_ a: String) -> String
{
return "\(a)\(a)\(a)"
}
Now we have useful implementations for all three of the p named types. Running the following code will make that clear in the console:
print(triple(3))
print(triple(3.0))
print(triple("3"))