Overloading functions with default parameter values

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.

Screenshot 2019-01-09 13.27.42.png

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.

Screenshot 2019-01-09 13.27.25.png

Here’s the conundrum.

What if both functions exist, as overloaded functions?

screenshot 2019-01-09 13.18.55

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?

giphy.gif

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“.

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

Tagged with: , ,
Posted in Swift

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: