Swift: Why You Should Love Default Parameter Values

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:

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.

UITableViewCell Function Swift

 

However, without a default parameter value, this would break my code anywhere I already use this function:

Swift No Default Parameter

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:

default value swift
Now, I can reconfigure which part of my application decides to actually set the color:

Configure Cell Swift

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:

Swift Default Parameter Values

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.

Swift Programming Language

Hope you’re enjoying Swift as much as I am!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.