Android App Development
iOS App Development
Flutter App Development
Cross Platform App Development
Hire on-demand project developers and turn your idea into working reality.
Big thanks to Webkul and his team for helping get Opencart 126.96.36.199 release ready!
Updated 29 October 2021
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:
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,
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.
Your email address will not be published. Required fields are marked*
Save my name email and website in this browser for the next time I comment.
Be the first to comment.
Enquiry or Requirement
If you have more details or questions, you can reply to the received confirmation email.