PRIMARY ASSOCIATED TYPES in Swift

Updated 30 December 2022

Save

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.

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:

In above code we are using ‘some’ keyword which is more descriptive. The above code snippet is equivalent to below code.

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:

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

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home