Associated Type

When defining a protocol, it’s sometimes useful to declare one or more associated types as part of the protocol’s definition. An associated type gives a placeholder name to a type that’s used as part of the protocol. The actual type to use for that associated type isn’t specified until the protocol is adopted. Associated types are specified with the associatedtype keyword.

high quality rolex replica swiss watch outlet replica replica master watches dhgate iced out rolex

Adding Associatedtype to our code is a way to create more generic protocols and as a result to make them more flexible. 

For example, you want to create a protocol that gives those who implement it some functionality, but at the same time, you want to give them more freedom to make these actions with different types.

Example

Let’s simulate something like this and write a protocol to understand better how to use it in practice.

  • We create two models: Customer & Car. 
  • We create WebServiceProtocol
  • Now we create class CarService which implements WebServiceProtocol and its functions.

The problem we want to solve

Until we get to line 37 it seems that all is good, but we need a CustomerService to fetch the customers. And here the problem begins. The WebServiceProtocol that we created has a func to get allCars. So what do we do? Add another func for Customers to WebServiceProtocol? Or Create Another protocol that makes the same logic but only returns Customers? We can do it but it will repeat the same code again for every Model that we want to fetch. How we can make WebServiceProtocol more generic?

The solution

The solution is to add associatedtype to the protocol. This type will be changed in every class that will use this protocol. What it means is that every time a class implements this WebServiceProtocol you need to specify which type you want to use. The way you do it is by creating typealias that specify to protocol to what his associatedtype is equale. And there it is, now the protocol knows the type that associatedtype equals to. In every place in that protocol instead of associatedtype it will use the type you set up.

And now your code will be more generic.

Summary

It seems that all is good, but there are consequences to using this method, with little flaw. 

To Understand what is the problem and how to solve it read about opaque type.

Leave a Reply