I wonder what makes two "similar functions" different with each other and can be called unambiguously
This is what I've learned from self-study
The uniqueness comes from: Function name + Argument order and argument name + return type. The combination of them must be unique to be able to make the function unique (Please see the example below)
Nmu1
andNum2
would cause ambiguous, because the return type (doesn't has the so called return name, the function name already act as this role) is not referred when calling a functionAlthough
Num3
function has a different parameter name, it won't uniquely separate it from the function inNum1
andNum2
. Because the argument name won't referred when the function had been called therefore, only a different argument name won't make a function unique; And the function inNum4
is different with all functions above, because its signature Function name + Argument order and argument name + return type is unique among all previous 3 functions.Num5
andNum6
functions are different with each other, for they have different argument orders when they were defined//Num1 func foo(guy name: String) -> String { return "Hi \(name)" } //Num2 func foo(guy name: String) { print("Hi \(name)") } //Num3 func foo(guy called: String) -> String { return "Hi \(called)" } //Num4 func foo(dude name: String) -> String { return "What's up \(name)" } //Num5 func foo(man name: String, from place: String) { print("Hi! I'm \(name) I come from \(place)") } //Num6 func foo(from place: String, man name: String) { print("Hi! I'm \(name) I come from \(place)") }
Question: I might miss or possibly even misunderstood some parts. It would be very nice of you that you can correct me and add the parts I missed
Thanks
[Update] Let's discuss a bit more on this issue. Let's started with the question that discuss the difference between Argument and Parameter. This question makes a lot of sense here!
Back to the quote from the official swift document
Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.
Argument, Parameter, Argument Labels and Parameter Names are different. The difference here can be used to differential functions.
Functions with same parameter name, same parameter order, same return type and even same function body can be differentiated from different argument Labels.
func foo(dude name: String) -> Int {
print("Hi \(name)!")
return 1
}
func foo(man name: String) -> Int {
print("Hi \(name)!")
return 1
}
//foo(dude: String) & foo(man: String) is identical when calling
For more information please address to Multiple functions with the same name