Parameter packs are a cool new feature of Swift 5.9, but surprisingly there doesn't seem to be a lot of discussion about them, and I hadn't seen this question answered on StackOverflow.
Is it possible to iterate over the arguments of a Swift parameter pack?
532 views Asked by Gregory Higley At
1
Since I hadn't seen this question answered, I thought it would be useful to demonstrate how to do this. Swift 5.9 has no built-in way to iterate over parameter pack arguments, but we can do it as a side-effect of creating a tuple, discarding the tuple result if we don't need it.
The function above counts its arguments. Not terribly useful, but if we modify it just a bit, we get a function that can count the number of elements in any tuple.
There are all sorts of more advanced things we can do with this technique, often using helper functions or closures. For example, here is code from a parser combinator package I've written in Swift.
This combinator takes a variadic argument list of parsers with potentially different output types and returns them as a tuple. As with any parser combinator framework, the next parser starts parsing where the previous parser left off (assuming it succeeds). The helper function modifies the
range
using aninout
parameter and keeps things moving along.The main point is that when Swift "executes" the parameter pack, it calls each element in order, and we can take advantage of that to simulate iteration.