Member-only story

Default arguments in Swift

Create a flexible API

Steven Curtis
3 min readSep 23, 2020
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

A simple example

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

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.

Creating a default parameter

The best thing about this default parameter is that it won’t change any existing calls to…

--

--

No responses yet