Start a Project

Associated Types in Swift Protocols

Associated Types in Swift one of the best way to define the protocols that can be reused among multiple different types. It works very closely together with protocols. The actual type to use for that associated type can’t specified until the protocol adopted. It is specified with the associatedtype keyword.

The protocol can only used as a generic by associated type. It prevents writing duplicate code by making it easier to define a common interface for multiple scenarios. From that way, the same logic you can be reused for multiple different types and allowed to write and test logic only once.

Here’s the protocol syntax with associatedtype:

Implementation of Associated Types

First, we’re going to extend the Vehicle protocol and it has an associatedtype called Type. Vehicle protocol that can store any type those items depend on whatever conforms to the protocol, but we can still use them inside the protocol and any extensions.

Now conform to the Vehicle protocol on ByRoad, BySKy and ByWater struct. All are different types as

Let’s handle the cases for Vehicle protocol.

Now we’re going to define a function like this:

The returns a value of type Vehicle and uses some keyword to denote that this is an opaque type. Above written function returning the different values in the bodies. Output as,

Conclusion

I hope this blog will help you in the understanding of Associated Types in Swift Protocols if still you have any comments, questions, or recommendations, feel free to post them in the comment section below!

For other blogs, please click here.

Exit mobile version