So one of my current favorite features of Swift is the ability to set default parameter values in functions. That’s because default parameter values make it very painless to add additional parameters to an existing function.
As developers, our code is always evolving. Features are added, and existing infrastructure is constantly modified to keep up with the latests requirements. So a function that starts out with only a few required parameters might grow a bit, and default parameter values make it very easy to accommodate this type of change.
In my Seinfeld Quotes app, for example, I have a very simple configure method for the QuoteTableViewCell:
<img class="alignnone wp-image-4423" src="http://natashatherobot.com/wp-content/uploads/Screen_Shot_2014-08-10_at_5_23_32_PM-1024x637.png" alt="Swift TableViewCell Function" width="589" height="366" />
Currently, the configure function takes in only one parameter – a quote object. But let’s say I want to make my tableView more readable by adding a slightly different background color to every alternating cell.
I can now add a color parameter to my configure function.
However, without a default parameter value, this would break my code anywhere I already use this function:
By setting the default value for the color parameter, all the places where the cell is configured continue working without any errors. In my case, I just set the color value to white as the default:
Now, I can reconfigure which part of my application decides to actually set the color:
Following this pattern, when the product owner or designer comes and requires the alternate cells to be black with white text color, with default parameter values, you only need to make the change where it’s needed:
As you can see, refactoring and adding additional features to your Swift function will be really nice with default parameter values.
The only thing to keep in mind with default parameter values is the following note from Apple:
Place parameters with default values at the end of a function’s parameter list. This ensures that all calls to the function use the same order for their non-default arguments, and makes it clear that the same function is being called in each case.
Hope you’re enjoying Swift as much as I am!