I’ve given this some thought, and it occurs to me that there are two common requests people have for variadics. If we are going to overhaul the current system to implement one, I think it is worth acknowledging both. I feel they are best summarized in terms of other ways to implement or approximate them.
-
func foo<E: Sequence>(vals: E)
Many programmers (possibly just myself, but I think this is common) want shorthand for expressing an arbitrary sequence[1] of values, which is what all variadics in Swift currently do, without requiring the use of this shorthand. For instance, the ability to pass either a variable number of
Element
instances or oneSequence
ofElement
instances, possibly even lazy.Right now, this is impossible: a variadic function cannot be called with some
Sequence
instance, even though many (I’d wager most) would work as written if given one. For obvious reasons, all of them would work as written if given anArray
, though this is currently prohibited for various reasons[2]. -
func foo<E: TupleLike>(vals: E)
The main goal of this pitch, with generic parameter packs, is to allow for arbitrary heterogeneous values to be passed to a function. This is very similar to accepting any tuple, as tuples are composed of a certain number of ordered values of certain types. Indeed, the main difference with parameter packs is simply the ability to add type constraints and otherwise work with them without specifying their exact composition.
To me, this is effectively an existential: nothing is required of the values except their conformance to certain protocols, and that means they must be treated in the body accordingly. In contrast to standard associated types, references to specific implementations can’t be easily made (you don’t even know if there are any implementations, let alone how many), and without requiring the implementations to be the same a lot of functionality is demonstrably impossible.
Both directions are useful, though not necessarily in the eyes of the same people. This pitch is about #2, but I think #1, where the variadic is mainly intended as shorthand for a sequence, should be kept in mind as a common use.
-
Certain uses may obviously warrant stricter requirements, particularly
Collection
or evenRandomAccessCollection
, but a lot of things don’t. ↩︎ -
Many of these reasons are relevant to proposals here: potential ambiguity about nesting, optimizability at compile-time, etcetera.
I think the latter is only solvable by improving the generics model to have protocols with associated values (i.e. a fixed-size array), which is way beyond the scope of this pitch. It is telling that C’s fixed-size arrays are currently imported as tuples. ↩︎