Generic Protocols
I believe we have the knowledge of Generics and we already know the benefit of using generics in our code. When we combine generics with protocols to make protocols generics that really gives us awesome feeling get rid of same and repetitive code ina away. but there are some techniques we apply to make the protocol generic.
But the question is why we really do it? if we understand that we would definitely be in love with this to make the protocols generic and using protocols in our code
I will say there are two reasons
- In a way for meeting the Open closed principles of SOLID principles and
- Giving control to classes or structs, which are conforming to the protocols.
This makes the component that we are writing flexible and extensible.
There are two ways we can create generic protocols
- By using Self
- By defining an abstract associatedtype
Let’s see how we use Self to create and use it.
If we are trying to return using Self in that case, the protocol will not be a generic one. The only way to make it generic is using Self in parameter or as the type of get set variable
Get Saurabh Shrivastava’s stories in your inbox
Join Medium for free to get updates from this writer.
Implementation of generic Protocols using associated types.
associatedtype is a very powerful keyword to make the protocol generic.
It might seem to be confusing a bit without any example, so let’s see an example of how we create the generic protocol with associatedtype.
If we see the declaration of the protocol, we have used the associated type to define the type that the class or struct, which conform to the generic protocol, will use. We can also define some variables using the associated type. If we see the implementation of the class IntClass there we have given data type to the associatedtype as Int and by default, someVar declared in the variable will use Int as type if we give some different type to it it will throw an error.
Writing code using Generic protocols is a powerful way to navigate away from repetitive code and have much of the overhead of maintenance. It can be used in cases like
- If we have to insert some data into Database.
- if we have to parse the data coming from Server.
These are just a few examples there can be a much bigger area of implementation using generic protocols.





