Intro to Protocol Oriented programming
Apple had added a new feature to the protocol i.e. protocol extension.While it may only seem like a minor feature at first, but this improved feature in swift allow us for a new type of programming i.e. protocol-oriented programming.
Protocols are not new to iOS developer but the idea that we can extend an existing type to adopt and conform to a new protocol, even if you do not have access to the source code for the existing type. Extensions can add new properties, methods, and subscripts to an existing type, and are therefore able to add any requirements that a protocol may demand.
Now let understand protocol-oriented programming by a simple example:
This defines a simple protocol Vehicle with some properties.
Now let extend this protocol with two common feature i.e. starting and stopping a vehicle.
Now, any type that conforms to the Vehicle protocol will automatically receive the start() and the stop() methods. You may have noticed that I provided a function definition rather than a function declaration.
Next, create a structure that conforms to Vehicle protocol.
Now suppose there is a class called Factory that simply creates Car and test it.
What make protocol-oriented programming different from object-oriented programming.
- Protocol-oriented programming should start with a protocol rather than a superclass.
- We can use protocol extensions to add functionality to the types that conform to that protocol rather than subclassing and adding functionality.
- Use of value types(struct,enum,etc.) rather than reference types(class).
References