Here’s a Swifty conundrum for you!
First a quick recap. Here’s a simple function with no parameters. Call it and “Hello World” will print to the console.
Here’s another function with the same name. This time it has a parameter with a default value. We can call it in exactly the same way, and the default value will be printed to the console.
Here’s the conundrum.
What if both functions exist, as overloaded functions?
What would we expect to see in the console?
We have two overloaded functions, one with a parameter with default values and another with no parameters. The call to the function could theoretically call either, but the question is, which does the compiler choose to call?
Need some thinking time?
So! It turns out that the console will display “Hello Mars”!
The rationale seems to be that the function with fewer parameters is called. I’m not able to find a discussion of the Swift team’s reasoning behind this, but it is consistent with the ‘overload resolution’ decision made by the C# compiler. The philosophy is described here in Microsoft docs:
If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call.
(“Optional parameters” in C# parlance are the equivalent of parameters with default values in Swift.)
If you would like a quick recap of overloading functions and default parameter values, check my previous blog post “Lightning tour of functions in Swift“.