Does swift support type pack for associated type?

I tried to create a protocol with a variadic associated type. It seems like swift doesn't not support it.

I know i can do that for struct and class:

struct Box<each E> {
    var values: (repeat each E)

but for protocol:

protocol BoxProtocol<each Element> {
    associatedtype Element
    var values: (repeat each Element) { get } 

It doesn't seem work.

1 Like

The angle brackets don't mean the same thing in the declaration of a protocol as it does in the declaration of a type. In the context of a protocol declaration, they are used to name one or more associated types as primary associated types. So, one can only repeat something that's declared in the body of the protocol as an associated type in between the angle brackets (that is, Element, not each Element).

This brings us to the second limitation: Swift does not allow us to declare a pack of associated types in the body of the protocol either; that is, one cannot write some permutation of associatedtype repeat each Element.

Third, at the use site, Swift does not permit a naked type pack (as opposed to a tuple) as a type; therefore, if there is only one primary associated type, one cannot write any BoxProtocol<Foo, Bar, Baz>. Instead, it must be BoxProtocol<(Foo, Bar, Baz)>.

1 Like