Default arguments in Swift

Create a flexible API

Image for post
Image for post
Photo by Moon on Unsplash

Default arguments are great! This article explains what they are, and why they are fantastic. Go on, take a look!

Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.5, and Swift 5.2.4

Prerequisites:

  • For simplicity this article is written with the Swift Playground in mind.
  • Some experience of functions is assumed

Functions

Imagine that we have a function that prints a name and a message to the console. That function looks like the following:

Image for post
Image for post
Click for Gist

This gives us an opportunity: surely in almost every case we are going to to have the “Hello, World” message (ok, a stretch but bear with me) — so we want “Hello, World” to be the default of the function. Is this possible? It turns out that yes, yes it is.

The best thing about this default parameter is that it won’t change any existing calls to the function — that is, they will still work!

Image for post
Image for post
Click for Gist

That means the code written above outputs the following two lines: Kyrone Hello, World Tarik Hello, to you too!

So if you have a public API ( you might want to read up about Access Control to think about this)

Initialization (Class and Struct)

Initialization similarly can benefit from default parameters.

Since we should always assume people are 21 if we don’t use their age (Note: This doesn’t apply to children, although the following Class does not reflect that) if the API user doesn't provide an age we set it to 21.

Image for post
Image for post
Click for Gist

This produces the following output: Chau 21

We can apply the same for Struct objects too!

So default parameters can be used…

Anywhere in the list of parameters Can be used for 0 or more of the parameters To enable API users to access functions; some might use a “simpler” version of the same API, that is complexity is reduced.

Conclusion

You might like to use default parameters to make the use of public APIs rather more easy for your client to use. However, you should make access as easy as possible, and you should do this by making your code as readable as possible as this will make your code as easy to be created and maintained in future.

If you’ve any questions, comments or suggestions please hit me up on Twitter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store