Swift Protocol with Associated Type

Karthik
2 min readJul 21, 2021

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.

Encoding dictionary into 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.

Encoding struct object into data

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 CanEncoderprotocol 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 😎.

--

--