In this article, we gonna inflate the power of protocol using associated types. let's dive in.
In search of reusability, we got genericsđ . Associated Types are like generics for protocols with which you can enhance the power of protocols.
Defenition
An associated type can be seen as a replacement of a specific type within a protocol definition. In other words: itâs a placeholder name of a type to use until the protocol is adopted and the exact type is specified.
Without talking much, let dive into the real example which we have used to solve the encoding issues with our application.
Real-Life Example.
In Swift world, data can be in any form like a dictionary ([String: Any]), struct object (POJO), etcâŚThe problem comes when converting this to foundation format which is nothing but data. so how the associated type helped us to tackle these issues is shown here.
we have created a protocol with associate type which enforces us to provide the object format that can be encoded as data.
JsonEncoder, which helps us converting dictionaries into data. typealias Object = [String: Any]
which can be removed, since swift tries to info the object format from the encode function itself.
Swift offers codable features from swift 4+, and itâs been effectively used in our entire application for API data conversion. Hence we are forced to convert the struct object to data while contacting the server. Associated type rescued us here on the data conversion. we simply adopted CanEncoder
protocol to define the type of object which can be encoded. That's it.
if incase in future any new type comes, and it needs an encoding, we can simply adopt the protocol which enforces us give the data type that needs to be encoded.
Conclusion
Associated types allow us to create more adaptable and flexible codes. The benefits of an associated type should become visible once you start working with them. They prevent writing duplicate code by making it easier to define a common interface for multiple scenarios. This way, the same logic can be reused for multiple different types, allowing you to write and test logic only once
âBe the senior engineer you needed as a junior.â â Someone
Thank you for reading the post, leave a comment with which you are using to make the code reusable đ.