There is a great programming paradigm called OOP, where objects are created to write code, similar parts are abstracted to reduce the amount of code and make it more universal. Most modern languages support OOP. Swift goes beyond OOP and supports POP because of the limitations of inheritance, and the excellent abstraction that can be applied not only to classes but also to Struct.
The advantages of OOP are:
- Encapsulation: Ability to hide properties and actions that control them
- Access control: Controlling access to objects
- Abstraction: Ability to extract common properties
- Polymorphism: Using one form to use objects of multiple types
Disadvantages of OOP include:
- Implicit Sharing: Sharing all properties and actions that were inherited unintentionally.
- Monolithic: There is only one parent, and inheritance can be done only once.
- Class Type Relationship Issue: To perform a reference to a complex inheritance structure or operation, downcast is required to obtain the correct type of any class.
- Class Cost Issue: Classes are more expensive than Structs, and there are cases where inheritance must be done with class even if it can be done with Struct.
POP can be thought of as a way to overcome this. POP allows for abstraction by adopting a protocol even for Struct. In other words, it is a feature that can easily express HAS-A relationships. POP helps to describe objects with Composition, which is a horizontal structure expression compared to OOP inheritance, which is a vertical structure expression. By adopting it, types can be extended.
Compared to OOP:
- Horizontal extension is possible. OOP can be a heavy abstraction in a vertical structure.
- Multiple protocols can be adopted, like multiple inheritances.
- Also supports class, struct, and enum.
For example, suppose there is a function that hides and shows views. If I want to create a view that hides it first and then shows it, with OOP, it would look like creating a HidableView and then creating a ShowableView that inherits it. However, inheritance can become complicated over time, making it difficult to find the parent or which exact inheritance is being received. With POP, it can be done more easily.