Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 146 ยท Protocols and Generics

Parameter Packs

Learn Swift parameter packs and variadic generics: each and repeat, type packs, value packs, pack expansion, shape errors and constraints, with examples.

A generic function such as func swap<T>(_ a: inout T, _ b: inout T) works for any one type. But what if you want a function that takes any number of arguments, each with its own type? For years the standard library solved this by copy-pasting: comparison of tuples exists for 2, 3, 4, 5 and 6 elements, and for nothing larger. SwiftUI's ViewBuilder had a similar ladder of overloads that stopped at ten views.

Parameter packs (Swift 5.9, with more power in Swift 6) remove that ceiling. A pack is a list of types, or a list of values, whose length is not fixed. You write the code once and the compiler generates the right version for each call. This lesson shows the two keywords you need, each and repeat, and the rules that keep packs type safe. It builds on Generic Functions, Generics and Tuples.

Type packs and value packs

Two words do all the work:

  • <each T> declares a type pack called T: zero or more types.
  • repeat each T in a parameter list means "one parameter for every type in T". The parameter that results is a value pack.

Inside the function, you cannot use a value pack like a normal variable. You must say each x for "one element of the pack" and wrap that in a repeat that says "do this once per element". Think of repeat as a loop that the compiler unrolls for you.

Swift Your first parameter packs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Four ideas are packed into that program.

  1. Iterating a pack. for item in repeat each items runs the body once per element. The type of item changes on each pass (Int, then String, and so on), yet everything is checked at compile time.
  2. Packs inside tuples. The return type (repeat each T) means "a tuple with one element per type in T". Calling tupleOf(1, "a", true) gives (Int, String, Bool), and the program prints (1, "a", true) (Int, String, Bool). A pack turns an argument list into a tuple and back.
  3. A repeated statement. repeat result.append(String(describing: each items)) is not a loop you wrote. It is one statement that the compiler expands into one append per element. That is why it can mix types freely: each expansion is its own type-checked statement.
  4. An empty pack is legal. printAll() prints nothing, and count() returns 0.

There is no .count on a pack, so the count function above uses the common trick of iterating and incrementing.

Packs have no runtime representation as a collection. You cannot index them, store them in an array, or return them as a value. They exist only so that repeat can expand them, which also means they cost nothing: the compiler turns the code into ordinary specialized code.

Several packs and their shape

A function can have more than one pack. Then a new question appears: do the packs need the same length? The shape of a pack is its length (plus any nested structure). When you expand two packs in one repeat, the compiler pairs the elements one by one, so their shapes must match.

Swift Pairing two packs element by element

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The result type (repeat (each A, each B)) is a tuple of tuples: the first element of A with the first element of B, then the second with the second. The output is ((1, 2.5), ("x", false)). Two types came in per position, and one tuple per position came out.

Note the argument label with:. A parameter that follows a variadic one must be labelled, otherwise the compiler could not tell where the first pack ends and the second begins. Without the label you get error: a parameter following a variadic parameter requires a label.

What happens when the shapes differ

Give the function two values in the first pack but only one in the second:

Swift Packs of different lengths (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler rejects the call at main.swift:8:11 with error: global function 'pairUp(_:with:)' requires the type packs 'Int, String' and 'Double' have the same shape, and adds a second error, missing argument for parameter #2 in call. Both say the same thing from different angles: you promised pairs, but there is a first element without a partner. Because shapes are checked at compile time, a mismatched pairing can never crash at run time.

Constraints on every element

A constraint on a pack applies to each element. Write <each T: Equatable> and every type in the pack must be Equatable.

With that, you can generalize something the standard library only does up to six elements: compare two tuples. Here two packs of the same type list are zipped in one repeat, and the loop exits early on the first difference:

Swift Comparing any number of values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

It prints true, false, 6 and [true, false, false]. The collections in totalCount are an array, a string and a dictionary: three different types, and all three have .count because they are Collections. The constraint is what lets the compiler accept (each items).count.

Reusing the same pack T for both left and right also forces them to have the same types in the same order. That is stronger than needing the same length, and the compiler checks it for you.

Packs in generic types and closures

Types can have packs too. Here a Row holds a tuple of values with a different type for each column and can print them without knowing how many there are. The second function accepts a closure whose parameters are the same pack as the arguments that follow it:

Swift A generic struct and a closure that takes a pack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Row(1, "Ada", true) infers Row<Int, String, Bool>, and the output is 1 | Ada | true. The last line prints x5. The generic call forwards its arguments with function(repeat each args): the expanded pack becomes an ordinary argument list. This "forwarding" pattern is the main reason packs exist, since wrappers such as logging, retry or memoizing helpers must accept arbitrary signatures.

Another way to spell a sum

Constraints can be as specific as you like. This function adds up integers of mixed widths by converting each one to Int:

Swift Mixed integer types in one call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The answer is -5. Each argument keeps its own type until Int(each values) runs. Had you constrained with Numeric instead, the conversion would not compile, because Numeric does not promise an Int conversion.

The most common mistakes

Packs have a few traps that trip beginners.

Forgetting each. A value pack is not a value you can name freely:

Swift Using a pack without each (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler answers main.swift:2:11: error: value pack 'each T' must be referenced with 'each'. Write repeat print(each x) if you want one print per element.

Using repeat where Swift has nowhere to expand it. An expansion is allowed in a parameter list, a tuple, a function call argument list, a generic argument list, or as a statement, but not as a stand-alone expression. Writing let y = repeat each x fails with pack expansion 'repeat each T' can only appear in a function parameter list, tuple element, or generic argument of a variadic type. If you need a result, make a tuple: let y = (repeat each x).

Expecting to store functions with a pack in an array. [(repeat each Payload) -> Void] looks natural for an event system, but at the time of Swift 6.3 the compiler reports cannot fully abstract a value of variadic function type for it, and some variants crash the compiler. Store a single closure, or wrap the payload in one tuple type.

Packs are not collections. There is no map, no index, no count, and you cannot pass a pack to another function as a unit. You expand it each time you use it. If you want collection behaviour, convert the elements into an [Any] or an array of a common protocol.

When packs are the right tool

Use packs when a function or type must accept several values of unrelated types and keep each type. Typical cases are forwarding wrappers, builder-like APIs, zipping and comparing, and result-builder buildBlock overloads (see Result Builders). Avoid them when a plain array of one protocol would do, or when the values really are of one type: [Int] or a variadic Int... is simpler to write and read.

On performance, packs are resolved at compile time and specialize like normal generics, so they are not slower than hand-written overloads. For compile times and readability, keep pack functions small and put the interesting logic in ordinary helper functions that each call receives.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does func f<each T>(_ items: repeat each T) accept?

    each T declares a type pack and repeat each T creates one parameter per type, so every argument keeps its own static type.
  2. 2. What is the type of (repeat each T) when T is Int, String, Bool?

    A pack inside a tuple becomes a tuple with one element per type in the pack.
  3. 3. Which error appears for pairUp(1, "x", with: 2.5) when pairUp zips two packs?

    Shape checking is compile-time. Expanding two packs together requires them to have the same length.
  4. 4. What does <each T: Equatable> constrain?

    A constraint on a pack applies to every element, which is why you can call != on each one.
  5. 5. Which is a valid way to use a value pack items inside the function body?

    Packs are only used through each inside a repeat expansion; they have no indexing and no count.

Summary

  • <each T> declares a type pack; repeat each T in a parameter list creates a value pack with one parameter per type.
  • Inside a function you use a pack with each x inside a repeat expansion or a for item in repeat each x loop.
  • A pack can become a tuple, (repeat each T), and a tuple of pairs, (repeat (each A, each B)).
  • Packs expanded together must have the same shape, and the compiler enforces it with a clear error.
  • A constraint such as each T: Equatable applies to every element.
  • Packs work in functions, structs, closures and forwarding calls (function(repeat each args)).
  • They are not collections: no index, no count, and you cannot store functions with packs in arrays today.
  • Choose packs for unrelated types of unknown count; use arrays or plain variadics for one type.

Next: Macros