Tuple splatting in Swift

Toby O'Connell
2 min readAug 28, 2021

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 to generate personalised greetings. One common way to achieve this would be to use the map higher order function like so:

We can make this more concise however by utilising tuple splatting! This will allow our 2 argument function to take a tuple with 2 elements.

Tuple splatting allows us to pass the arguments through without having to extract them from the original data. Note that this can be done with other higher order functions such as filter, flatMap, forEach etc.

Direct splatting

It should be noted that direct splatting cannot work. If we try to call out makeGreeting function with a single tuple we get the following error:

Global function ‘makeGreeting’ expects 2 separate arguments

As we know, going through a little indirection like with the map function can solve this problem for us. The following function can be used to achieve that small amount of indirection required:

We can use this new helper like this:

Conclusion

We’ve seen how tuple splatting can be used with higher order function to make code more concise.

Use of the helper certainly make the call site more concise, but it could be argued that it hurts readability. Personally I quite like it, but let me know what you think in the comments :)

--

--

Toby O'Connell

Swift / iOS developer - I write about things that I find interesting or innovative.