What Is Splatting?

Argument splatting is the concept of extracting the parameters of an object to pass to a function automatically. In Swift this can be done using tuples.

Suppose we had some data and a function that looked like this:

We’d like to pass all our users through the makeGreeting function…

Recently I discovered that tuples can be used to easily and simply compare and equate multiple variables.

Take for example the implementation of Date and Comparable taken from the Swift documentation:

Apples implementation of Comparable

This compares the year, month and day in that order to determine which is greater (later). A simpler (and perhaps more readable) way of writing this same code is this:

Comparable using tuples

The tuple is compared in order of its variables so we achieve the same result.

As an added bonus, the same is true for Equatable conformance:

Equatable using tuples

This last one is a bit of a contrived example as Equatable conformance would be synthesised for Date anyway, but suppose we wanted to omit the year, to compare birthdays, it would be very easy to simply remove year from the tuples

Many swift developers will know that any function without an explicit return type specified will return Void.

Usually, ignoring the return type produces the following warning:

Ignoring the return type from a function

However, this is not the case for functions returning Void (or we’d have warnings everywhere!) This becomes clear when using the @discardableResult annotation:

Toby O'Connell

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