This is an advance topic and builds on last year’s “Embrace Swift Generics” it is highly recommended that you review this before watching this session.
What parameter packs solve
- This is about generics and variadics
- Code is written in values and types. You can abstract over types by having varying types, most generic code abstracts over types and values
- If you want variable number of parameters .. you have Variadic parameters. But they have limitations, you can’t know the number of parameters while preserving type information. The only way to do this now is via overloading.
- This pattern is limiting and adds redundancy.
- This solves the overloading pattern problem
How to read parameter packs
- In code a parameter pack can handle any qty or types,
- A type pack handles different types
- A value pack handles different values
- They are used together – they are positional, so at the type of position 0 is related to the value at position 0. Think of it like a collection.
- You need to iterate to process, but each element can have a different type. So you would define a pack like <each Type> – this is a type parameter type. Use singular instead of plural. So you then use repeat Function<each Type> to see how this replacement works. You will get a comma separated list of types. They can only be used In things that naturally support comma separated lists, like function parameters, etc.
- Using in a type pack in a function value, it becomes a value pack
- You can add constraints to a parameter pack to enable conformance
- You an force a minimum number of arguments (even though the default is zero or more arguments).
Using parameter packs
- To use this code, you will want to use repetition patterns like repeat (each item).evaluate() if you want a list of all the values you can wrap in parenthesis like (repeat (each item).evaluate())
- This should make your code simpler, and also allow you to write a lot less code
- To exit an iteration – use throwing methods to allow you to break out of the iteration loop (if needed)