In this post, we are going to discuss the primary associated types which are introduced in Swift 5.7.
In Swift 5.7, we can specify primary associated types with protocols.
So let’s discuss the Primary Associated Types in detail.
What are Primary Associated Types
The primary associated types are lot like the generics, with these we can specify the type for a given associated type as a generic constraint.
For Collection, the Swift library added a primary associated type for the Element associated type.
Let’s take a look at how a protocol defines a primary associated type.
1 2 3 4 5 6 7 8 |
public protocol Collection<Element> : Sequence { associatedtype Element associatedtype Iterator = IndexingIterator<Self> associatedtype SubSequence : Collection = Slice<Self> where Self.Element == Self.SubSequence.Element, Self.SubSequence == Self.SubSequence.SubSequence } |
In the above code, you can see that the protocol have multiple associated types, but as the Element is primary associated type it is not written between <>
We can use the above protocol in our code as below:
1 2 3 4 |
class Movies { func play(_ movieType: some Collection<Genere>) { } } |
In above code we are using ‘some’ keyword which is more descriptive. The above code snippet is equivalent to below code.
1 2 3 4 |
class Movies { func play<MovieType: Collection<Genere>>(_ movieType: MovieType) { } } |
Note that this also works with the ‘any’ keyword. For example, if we want to store our movie on our Movies, we could write the following code:
1 2 3 4 5 6 7 |
class Movies { var movieType: any Collection<Genere> = [] func play(_ movieType: some Collection<Genere>) { self.movieType = movieType } } |
I assume that you have knowledge about the ‘some’ and ‘any’ keywords. However, You can visit my blog if you want to read about the ‘some’ and ‘any’ keywords in Swift.
Conclusion
In conclusion, with primary associated types we can write descriptive and much more powerful code
Please visit the link for more information on primary associated types by donnywals