Why did Swift adopt POP?
Intro
As you know, Swift is based on POP(Protocol-oriented programming). POP increases the reusability of the codes, thereby helping to design a more productive and clean structure.
Today, I’ll discuss why Swift adopted POP instead of OOP(Object-oriented programming) and compare POP and OOP.
What is the key to POP?
Swift has a basic type based on the Struct. How can a Struct that can’t be inherited have so many different common functions? The answer lies in protocols and extensions. Here’s the sample code for using the protocol and extension.
protocol Swimable {
func swim()
}
extension Swimable {
func swim() {
print("swimming...")
}
}
protocol Walkable { func walk() }
extension Walkable {
func walk() {
print("walking...")
}
}
struct Person: Swimable, Walkable { }
let person: Person()
person.swim()
person.walk()
struct Turtle: Swimable { }
let turtle: Turtle()
turtle.swim()
If the protocol’s requirements can be implemented all at once in advance as an extension, duplicate code can be avoided. In other words, If you implement the protocol well in the initial implementation, as in the code above, you can use it just by adopting it.
If you need to do something different from the initial implementation of the protocol, you can just redefine the protocol’s requirements for that type.
The initial implementation of the protocol can be seen as the key to protocol-oriented programming.
What’s the difference between POP and OOP?
If you are familiar with Java, C++, and C#, You must know about OOP(Object-oriented programming). OOP and POP increase the reusability of the codes, thereby helping to design a more productive and clean structure. But there’s a difference between POP and OOP.
First, POP extends the type to a horizontally using Protocol. But OOP extends type to vertically with Subclassing.
Second, POP can be implemented with both reference/value types via Extension. But in OOP, Only reference type can be implemented.
Third, POPs can follow multiple protocols. But OOP only one superclass can be had, multiple inheritances are not possible.
The reason why Swift adopted POP
So why does Swift use POP(protocol-oriented programming)? In POP, Only the necessary parts can be separated by a protocol, and multiple protocols can be implemented. It can be applied to Class/Structure/Enum. That makes your code more light and fast.
But OOP expands the type through inheritance. As a result, sometimes unnecessary properties are obtained. Also, You can’t drag functions that belong to another inheritance system from one inheritance system. That’s the biggest difference between POP and OOP.
Conclusion
There is no absolutely good way of POP or OOP. It is important to use it appropriately according to the development environment and situation. However, since Swift adopts POP, iOS developers should be familiar with POP. and It is required to code while taking advantage of POP.