Understating primary associated types in Swift 5.7

To begin with the beginning, I'm not quite sure what primary associated types are in the first place.
I know they are marked by generics such as:

struct Collection<Element> {
     associatedtype Element
     ....
}

And that now you can do something like some Collection<any Type>, although that seems to introduce some unwelcomed complexity to me, because now I feel I could also write some Collection<any Type>? But probably that doesn't make any sense whatsoever. Not sure.

But my main question is what's the difference between an associated type and a primary associated type? And how does one distinguish between them?
Thanks!

every primary associated type (PAT) is an associated type, but not every associated type is a PAT.

where T:Collection<U>

is just syntactic sugar for

where T:Collection, T.Element == U
1 Like

I see, thank you! But if Collection already has Element as a generic parameter in angle brackets, why bother putting it as an associated type?

Collection is a protocol, it doesn’t (and can’t) have generic parameters. Protocols just have associated types, whether primary or not.

1 Like

I just found out about that! So the the only reason for "generics", aka bracket parameters in Protocols, at all, is that so you can write something like func returnACollection -> Collection <any SomeProtocol>? Or something similar.

Yup: swift-evolution/0346-light-weight-same-type-syntax.md at main · apple/swift-evolution · GitHub

I think the proposal tells everything about why this is awesome. Also because of this feature and some improvement to generics now it's more natural to work with combine and you don't need to put in this existential wrapper

// instead of this
var intPublisher: AnyPublisher<Int, Never> { 
  Just(1).eraseToAnyPublisher()
}

// you can just
var intPublisher: some Publisher<Int, Never> { 
  Just(1)
}
2 Likes