skip to content

How does a Swift logging helper declared `func logValues<each Value: CustomStringConvertible>(_ values: repeat each Value)` differ from one taking `Any...`?

level: seniorimportance: nice to knowfreq 20%

answer

  1. a list of types, not one
  2. each declares, repeat expands
  3. constraint applies element-wise
  4. types survive into the result
  5. for-in over a pack

basics

~20 s

each Value declares a type parameter pack. Every argument keeps its own static type, every one must meet the constraint, and repeat expands code per element. Any... erases every argument to Any inside an array and checks nothing at compile time.

solid answer

~40 s

Parameter packs, added in Swift 5.9, let one generic function take any number of arguments of different types. `each Value` names a pack of types, and `repeat each Value` expands it into one parameter per argument. The constraint applies to each element, so `logValues(42, "EUR", true)` binds the pack to `Int, String, Bool`, and an argument that is not `CustomStringConvertible` is rejected at the call. In the body, `repeat` evaluates an expression once per element, as in `repeat parts.append((each values).description)`. Since Swift 6.0, `for value in repeat each values` iterates the pack. Because the types survive, a pack function can return them, for example `-> (repeat (String, each Value))`. An `Any...` variadic parameter receives an `[Any]`: types are erased, any value is accepted, and using an element needs a cast.

code

swift · 21 lines
swift
func logValues<each Value: CustomStringConvertible>(
    _ label: String, _ values: repeat each Value
) {
    var parts: [String] = []
    for value in repeat each values {      // pack iteration, Swift 6.0
        parts.append(value.description)
    }
    print("\(label): \(parts.joined(separator: " | "))")
}

func labelled<each Value: CustomStringConvertible>(
    _ values: repeat each Value
) -> (repeat (String, each Value)) {
    (repeat ((each values).description, each values))
}

logValues("checkout", 42, "EUR", true, 3.5)
let row = labelled(7, "tea")
print(row.0.0, row.1.1)                     // 7 tea
let n: Int = row.0.1                        // element types survive
print(n + 1)

go deeper

for a junior

Recall that each declares a pack of types and repeat expands it, so one function can take differently typed arguments without Any.

for a middle

Explain how a constraint applies to every element, how a repeat expression runs once per element, and why Any... loses types.

for a senior

Show the limits: no pack-to-concrete same-type requirements, no where in pack iteration, the same-shape rule, and the iOS 17 floor for generic types with packs.

for a principal

Coach teams to adopt packs where an overload ladder or Any... is hiding type errors, and to keep public pack-based APIs simple for callers.

## The problem packs solve A logging helper wants any number of arguments of different types. Before Swift 5.9 the usual options were: - **`Any...`**: the body receives `[Any]`. Every argument's type is erased, nothing is checked at the call, and using an element needs `as?`. - **An overload ladder**: `log<A>(_ a: A)`, `log<A, B>(_ a: A, _ b: B)`, and so on up to some arbitrary arity. That keeps the types but caps the count and multiplies code. The standard library has the same limit in places: `zip(_:_:)` takes exactly two sequences. **Parameter packs** (Swift 5.9) give one declaration that abstracts over a **list of types** of any length. ## The vocabulary | Syntax | Meaning | |---|---| | `<each Value>` | declares a **type parameter pack**, zero or more types | | `<each Value: CustomStringConvertible>` | every type in the pack must conform | | `_ values: repeat each Value` | a **value parameter pack**, one argument per type | | `repeat expr(each values)` | a **pack expansion**, which evaluates `expr` once per element | | `(repeat each Value)` | a tuple of the pack's elements | | `where repeat each C: Collection` | an element-wise requirement in a `where` clause | `logValues("checkout", 42, "EUR", true)` binds `Value` to the list `Int, String, Bool`. It does not bind it to `Any`, to `[any CustomStringConvertible]`, or to one tuple type. ## Constraints on a pack - A constraint in the angle brackets or in a `where repeat each ...` clause applies to **each element**. An argument whose type does not conform fails at the call, for example "global function 'logValues' requires that 'Opaque' conform to 'CustomStringConvertible'". - A same-type requirement between a pack and a concrete type, such as `where repeat each T == Int`, is **not supported** in Swift 6.4. The compiler says "same-type requirements between packs and concrete types are not yet supported". When all the arguments share one type, `Int...` is the right tool. - Two packs expanded together must have **the same shape** (the same length). Otherwise the compiler reports that the pack expansion requires them to have the same shape. - A reference to a pack must sit inside an expansion. Writing `each T` without `repeat` is an error. ## Using the values 1. **Expansion expressions.** `repeat parts.append((each values).description)` runs the call once per element, in order. 2. **Pack iteration** (Swift 6.0). `for value in repeat each values { ... }` binds each element in turn. It supports `break`, `continue` and patterns, but **not** a `where` clause, which fails with "'where' clause in pack iteration is not supported". Elements are evaluated on demand, so the i-th element is evaluated on the i-th iteration, and a `break` skips the rest. 3. **Returning the types.** `-> (repeat (String, each Value))` returns a tuple whose element types match the arguments. `labelled(7, "tea").0.1` is an `Int`, with no cast. 4. **Single-element packs unwrap.** With one argument, `(repeat (String, each Value))` becomes `(String, Int)`, not a one-element tuple around it. ## Packs compared with `Any...` | | `repeat each Value` | `Any...` | |---|---|---| | inside the body | a pack, used through `repeat` or `for-in` | an `[Any]` array | | element types | kept statically | erased | | constraint | checked per argument at compile time | none | | using an element | direct, via the constraint | needs `as?` | | returning values | as a typed tuple | as `[Any]` | | indexing `values[0]` | not available | available | ## Limits and availability - **Generic types** with packs, such as `struct Row<each Column>`, need runtime support. Building one for an earlier deployment target fails with "parameter packs in generic types are only available in iOS 17.0.0 or newer" (macOS 14.0.0 for a Mac target). Pack **functions** compile for those older targets. - Packs abstract over **types**. **Integer generic parameters** (Swift 6.2), such as `struct Ring<let capacity: Int, Element>`, abstract over a **value**, which is used by `InlineArray<count, Element>`. They are different features. - Interviews rarely go past recognising `each`/`repeat` and explaining why packs beat `Any...`. Production code mostly meets packs through library APIs.

  • Can `where repeat each Value == Int` restrict every element of a pack to `Int`?
    No. Swift 6.4 rejects it with "same-type requirements between packs and concrete types are not yet supported". When every argument has the same type, a plain variadic parameter such as `Int...` is the right tool. Packs earn their keep when the element types differ and must be preserved.
  • Why does `struct Row<each Column>` fail for an iOS 16 deployment target while the `logValues` function builds?
    Generic types with parameter packs depend on runtime support that ships with iOS 17 and macOS 14. For an earlier target the compiler reports "parameter packs in generic types are only available in iOS 17.0.0 or newer". A pack function compiles for the same older target, so helpers like `logValues` are usable there.
  • What does `labelled(7)` return when the pack has a single element?
    `(String, Int)`. With one element, the parenthesised expansion `(repeat (String, each Value))` unwraps to the element itself instead of a one-element tuple. That is why `let one: (String, Int) = labelled(7)` compiles.

  • Any... keeps each argument's static type, so packs add nothing.
  • Inside the body, a value pack is an array you can index with values[0].
  • where repeat each T == Int forces every argument to be an Int.
  • A for-in over a pack accepts a where filter like any other loop.
  • A pack binds one shared type, so every argument must have the same type.

Assumes Swift 6.4: parameter packs arrived in Swift 5.9, for-in iteration over a pack in Swift 6.0, and generic types with packs need an iOS 17 or macOS 14 runtime.