Parameter packs (variadic generics)

suggest change

A normal generic function has a fixed number of type parameters. func pair<A, B>(_ a: A, _ b: B) takes exactly two values. If you want the same thing for 3, 4 or 10 values, you used to write one overload per arity. The standard library did this for tuple comparison (== works only up to 6 elements) and SwiftUI did it for ViewBuilder.buildBlock (up to 10 views).

Variadic parameters (Int...) don't help here. They accept any number of values, but all of the same type, collected into an array. Using Any... accepts mixed types but throws the types away:

func anyVersion(_ values: Any...) -> [Any] { values }
let lost = anyVersion("Ada", 36)
print(type(of: lost))
// let n: String = lost[0]  // error: cannot convert 'Any' to 'String'
Array<Any>

Parameter packs fix this. A function can take any number of arguments, each with its own type, and the compiler keeps track of every one of them. They were added in Swift 5.9 (SE-0393 for functions, SE-0398 for generic types). Swift 6.0 added for ... in repeat each to iterate over a pack (SE-0408).

The examples were compiled and run with Swift 6.4 on Windows:

swiftc -swift-version 6 main.swift -o main.exe

The syntax: each and repeat

func describe<each T>(_ values: repeat each T) {
    repeat print(type(of: each values), "=", each values)
}

describe(1, "two", 3.0, [4])
describe()

Output:

Int = 1
String = two
Double = 3.0
Array<Int> = [4]

There are three new pieces:

The call with no arguments is valid too. The pack is empty and nothing is printed.

It's a convention to give packs singular names (each T, each value) because each already says "every element".

Building tuples from packs

A pack is not a value you can store directly. To keep it, expand it into a tuple: (repeat each values). The return type uses the same syntax: (repeat each T) is a tuple with one element per type in the pack.

The pattern after repeat can be any type or expression that uses the pack:

func wrapInArrays<each T>(_ values: repeat each T) -> (repeat [each T]) {
    (repeat [each values])
}
let arrays = wrapInArrays(1, "a", true)
print(arrays)
print(type(of: arrays))

func optionals<each T>(_ values: repeat each T) -> (repeat Optional<each T>) {
    (repeat Optional(each values))
}
print(optionals(1, "x"))

func types<each T>(_ values: repeat each T) -> (repeat (each T).Type) {
    (repeat type(of: each values))
}
print(types(1, "x", 2.5))

let single = wrapInArrays(42)
print(single, type(of: single))

Output:

([1], ["a"], [true])
(Array<Int>, Array<String>, Array<Bool>)
(Optional(1), Optional("x"))
(Swift.Int, Swift.String, Swift.Double)
[42] Array<Int>

(repeat [each T]) with T = Int, String, Bool becomes ([Int], [String], [Bool]). Note the last example: a one-element tuple in Swift is just that element, so wrapInArrays(42) returns [Int], not a tuple.

The result is a normal tuple. The caller can destructure it and index it with .0, .1 because at the call site the types are concrete.

Iterating over a pack (Swift 6.0)

repeat works when the body is a single expression. For anything with statements, such as if, return or a running total, Swift 6.0 lets you loop over a pack with for value in repeat each values:

func count<each T>(_ values: repeat each T) -> Int {
    var n = 0
    for _ in repeat each values {
        n += 1
    }
    return n
}
print(count())
print(count(1, "a", true))

func firstString<each T>(_ values: repeat each T) -> String? {
    for value in repeat each values {
        if let s = value as? String { return s }
    }
    return nil
}
print(firstString(1, 2.5, "found", "later") ?? "none")
print(firstString(1, 2) ?? "none")

Output:

0
3
found
none

Inside the loop, value has a different type on each iteration. The body is type-checked once, generically, so you can only do with value what every element allows. Without constraints that is very little: print it, cast it with as?, pass it to another generic function. break, continue and return work as in any loop.

There is no built-in count of a pack and no way to index it inside generic code. (repeat each values).0 doesn't compile, because the pack could be empty. Iterate or expand instead.

Constraining the pack

A constraint on a pack applies to every type in it. Write it inline or in a where clause with repeat each:

func joined<each T: CustomStringConvertible>(_ values: repeat each T, separator: String = ", ") -> String {
    var parts: [String] = []
    for value in repeat each values {
        parts.append(value.description)
    }
    return parts.joined(separator: separator)
}
print(joined(1, true, 2.5, "hi"))
print(joined(1, 2, 3, separator: " | "))

func sumAll<each T: BinaryInteger>(_ values: repeat each T) -> Int {
    var total = 0
    for v in repeat each values { total += Int(v) }
    return total
}
print(sumAll(1, Int8(2), UInt64(3)))

func distinctCount<each T>(_ values: repeat each T) -> Int where repeat each T: Hashable {
    var set = Set<AnyHashable>()
    for value in repeat each values { set.insert(value) }
    return set.count
}
print(distinctCount(1, 1, "a", "a", 2.0))

Output:

1, true, 2.5, hi
1 | 2 | 3
6
3

Because every element is CustomStringConvertible, value.description compiles inside the loop. sumAll accepts integers of different widths in one call, which Int... can't do.

separator comes after the pack, so it must have a label. Swift needs the label to know where the pack ends.

What doesn't work yet is requiring every element to be one concrete type:

func g<each T>(_ v: repeat each T) -> Int where repeat each T == Int { 0 }
error: same-type requirements between packs and concrete types are not yet supported

For that, a plain variadic Int... parameter is the right tool anyway.

Several packs and the same-shape rule

A function can have more than one pack. When a repeat pattern uses two packs at once, they are expanded in lockstep, element by element. This requires them to have the same shape: the same number of elements.

func maxOfEach<each T: Comparable>(_ a: repeat each T, with b: repeat each T) -> (repeat each T) {
    (repeat max(each a, each b))
}
print(maxOfEach(1, "apple", 9.5, with: 3, "banana", 2.0))

func pairs<each T, each U>(_ first: (repeat each T), _ second: (repeat each U)) -> (repeat (each T, each U)) {
    (repeat (each first, each second))
}
print(pairs((1, "a"), (true, 2.0)))

Output:

(3, "banana", 9.5)
((1, true), ("a", 2.0))

In maxOfEach both packs use the same T, so they have the same types and the same length. In pairs the types can differ, but repeat (each T, each U) forces the lengths to match. The compiler checks this at the call site:

print(pairs((1, "a"), (true, 2.0, 3)))
error: pack expansion requires that 'Bool, Double, Int' and 'Int, String' have the same shape

Note that pairs takes tuples, not packs, as parameters. A tuple of a pack, (repeat each T), is a normal parameter, so two of them don't need labels and the caller can see where one ends.

Tuple equality of any length

The standard library defines == for tuples only up to 6 elements:

print((1, 2, 3, 4, 5, 6) == (1, 2, 3, 4, 5, 6))
print((1, 2, 3, 4, 5, 6, 7) == (1, 2, 3, 4, 5, 6, 7))
error: binary operator '==' cannot be applied to two '(Int /* ... repeated 7 times ... */)' operands

With a pack and iteration you can write one function that works for any length. for (l, r) in repeat (each lhs, each rhs) walks both tuples in lockstep:

func allEqual<each T: Equatable>(_ lhs: (repeat each T), _ rhs: (repeat each T)) -> Bool {
    for (l, r) in repeat (each lhs, each rhs) {
        if l != r { return false }
    }
    return true
}
print(allEqual((1, "a", 2.0, true, 5, 6, 7), (1, "a", 2.0, true, 5, 6, 7)))
print(allEqual((1, "a", 2.0, true, 5, 6, 7), (1, "a", 2.0, true, 5, 6, 8)))

Output:

true
false

Practical helper: unwrap all optionals

A common need is "give me all of these values, or nil if any is missing". Without packs you'd write a nested if let or one helper per arity. With a pack it's one function:

func unwrapAll<each T>(_ values: repeat (each T)?) -> (repeat each T)? {
    for value in repeat each values {
        if value == nil { return nil }
    }
    return (repeat (each values)!)
}

let name: String? = "Ada"
let age: Int? = 36
let email: String? = nil

if let (n, a) = unwrapAll(name, age) {
    print("\(n) is \(a)")
}
if let (n, a, e) = unwrapAll(name, age, email) {
    print("\(n) \(a) \(e)")
} else {
    print("something is missing")
}

func parseRow(_ fields: [String: String]) -> (String, Int, Double)? {
    unwrapAll(fields["name"], fields["age"].flatMap { Int($0) }, fields["score"].flatMap { Double($0) })
}
print(parseRow(["name": "Bob", "age": "41", "score": "9.5"]) as Any)
print(parseRow(["name": "Bob", "age": "old", "score": "9.5"]) as Any)

Output:

Ada is 36
something is missing
Optional(("Bob", 41, 9.5))
nil

The parameter pattern repeat (each T)? means "each argument is an optional of its own type", and the result (repeat each T)? is an optional tuple of the unwrapped types. The loop checks for nil first, so the force unwraps in the return line are safe. Comparing with nil works even when T isn't Equatable.

The same helper without pack iteration

If you need to support Swift 5.9 or 5.10, you can't use for ... in repeat. The usual trick is to move the logic into a small generic function and call it in a repeat expression. To stop early, the function throws:

struct Missing: Error {}

func unwrap<V>(_ value: V?) throws(Missing) -> V {
    guard let value else { throw Missing() }
    return value
}

func unwrapAll<each T>(_ values: repeat (each T)?) -> (repeat each T)? {
    try? (repeat unwrap(each values))
}

print(unwrapAll(1, "a") as Any)
print(unwrapAll(1, nil as String?) as Any)

Output:

Optional((1, "a"))
nil

(The typed throws(Missing) needs Swift 6.0; in 5.9 use plain throws.)

Practical helper: zip any number of sequences

The standard library's zip takes exactly two sequences. Here is a version that takes any number, of any types, and stops at the shortest one.

The tricky part is that the iterators must be mutable, and you can't mutate one element of a pack in place. The solution is to wrap each iterator in a closure that owns it, then call all closures with repeat and reuse unwrapAll from above:

func makeNext<S: Sequence>(_ sequence: S) -> () -> S.Element? {
    var iterator = sequence.makeIterator()
    return { iterator.next() }
}

func zipAll<each S: Sequence>(_ sequences: repeat each S) -> [(repeat (each S).Element)] {
    let nexts = (repeat makeNext(each sequences))
    var result: [(repeat (each S).Element)] = []
    while let row = unwrapAll(repeat (each nexts)()) {
        result.append(row)
    }
    return result
}

let names = ["Ada", "Bob", "Cy"]
let ages = [36, 41, 29, 50]
let admins = [true, false, false]
for (name, age, admin) in zipAll(names, ages, admins) {
    print(name, age, admin)
}
for (i, ch, n, s) in zipAll(1..., "xyz", stride(from: 10, to: 100, by: 10), ["a", "b"]) {
    print(i, ch, n, s)
}

Output:

Ada 36 true
Bob 41 false
Cy 29 false
1 x 10 a
2 y 20 b

(each S).Element reaches into the associated type of each sequence, so the second call returns [(Int, Character, Int, String)]. Every element type is checked at compile time. Even the infinite range 1... is fine, since the loop stops when the shortest sequence ends.

Typed key paths

Packs combine well with key paths. This function reads any number of properties at once and returns them with their real types:

struct User {
    var name: String
    var age: Int
    var tags: [String]
}

func pick<Root, each Value>(_ root: Root, _ paths: repeat KeyPath<Root, each Value>) -> (repeat each Value) {
    (repeat root[keyPath: each paths])
}

let user = User(name: "Ada", age: 36, tags: ["admin", "dev"])
let (name, tagCount) = pick(user, \.name, \.tags.count)
print(name, tagCount)
let picked = pick(user, \.age, \.name, \.tags)
print(picked)

Output:

Ada 2
(36, "Ada", ["admin", "dev"])

Root is a normal generic parameter shared by every key path, and each Value is a pack. A function can mix both.

Generic types with parameter packs

Structs and classes can declare a type pack too. A typical pattern is to store the values as a tuple:

struct Row<each Column> {
    var values: (repeat each Column)

    init(_ values: repeat each Column) {
        self.values = (repeat each values)
    }
}

extension Row: CustomStringConvertible {
    var description: String {
        var parts: [String] = []
        for value in repeat each values {
            parts.append("\(value)")
        }
        return "Row(" + parts.joined(separator: " | ") + ")"
    }
}

extension Row: Equatable where repeat each Column: Equatable {
    static func == (lhs: Row, rhs: Row) -> Bool {
        for (l, r) in repeat (each lhs.values, each rhs.values) {
            guard l == r else { return false }
        }
        return true
    }
}

let row = Row("Ada", 36, true)
print(row)
print(type(of: row))
print(row.values.0, row.values.1)
print(row == Row("Ada", 36, true))
print(row == Row("Ada", 37, true))

Output:

Row(Ada | 36 | true)
Row<Pack{String, Int, Bool}>
Ada 36
true
false

Notes:

When to use parameter packs

For the basics of generic functions and constraints, see The Basics of Generics and Advanced Type Constraints.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents