WWDC Digest: Parameter packs in Swift

This blog post is basically a summary of the WWDC video that talks about parameter packs in Swift. Since the video is chock-full of info, I figured it’d be really handy to have all that stuff written out for easy reference

Purpose of parameter packs

Parameter packs are like superheroes for tackling the challenge of dealing with multiple input parameters. Imagine you’re trying to create a function that can smoothly handle all sorts of different input parameters. Currently, you’d have to create a bunch of overloaded functions, each accommodating a different number of input parameters.

But here comes the cool part: Swift 5.9 swoops in with the introduction of parameter packs! These nifty things make solving this issue a whole lot fancier. Instead of juggling tons of overloads, you can handle this situation in a much more elegant and streamlined manner. It’s like giving your code a stylish upgrade!

Parameter pack overview


Parameter packs are like magical containers that can hold a bunch of types and values, all bundled up nicely to be handed over to a function as a single package.

Now, there are two main flavors of parameter packs: type packs and value packs.

Type packs are all about holding different types. They’re like your toolkit of various types, ready to be used when needed. For example, you can have a type pack that includes integers, strings, and maybe even some custom types.

(Bool, Int, String)

Value packs are all about holding individual values e.g

(true, 10, "")

Type packs and value packs are used together so type packs provides each individual type for each individual value in a value pack. Corresponding type and value are at the same position in their respective packs.

Defining parameter packs

Pack of type parameters are defined with each keyword e.g

func query<each Payload>

Repetition pattern is expressed using repeat keyword followed by type called pattern type e.g repeat Request<each Payload>. repeat indicates that the pattern type will be repeated for every element in a given argument pack.

each acts as a placeholder that is replaced with individual pack elements at every iteration

Example

Let’s start with this sequence:

each Payload = Bool, Int, String
repeat Request<each Payload>

The pattern will be repeated three times and will unwrap to something like this:

Request<Bool>, Request<Int>, Request<String>

<each Payload> is replaced with the concrete type in the pack during each repetition. The result is comma separated list of types so it can be used only in positions that naturally accept comma separated lists e.g types wrapped in parenthesis (tuple type or a single type), function parameter lists, generic argument lists.

Leave a Reply

Your email address will not be published. Required fields are marked *