Swift — Protocol oriented programming


Protocol oriented programming (POP)

  • It is a programming paradigm of swift, which was proposed by Apple at WWDC in 2015
  • In Swift’s standard library, you can see the shadow of a large number of POPs
@Frozen public struct int: source code definition of fixedwidthinter, SignedInteger // int

At the same time, swift is also an object-oriented programming language (OOP)

  • In swift development, OOP and pop complement each other, and neither side can replace the other

Pop can make up for some design deficiencies of OOP

OOP has three characteristics: encapsulation, inheritance and polymorphism

  • Inherited classic usage
    -When multiple classes (such as classes a, B and C) have many commonalities, these commonalities can be extracted into a parent class (such as class D). Finally, classes a, B and C inherit class D

However, there are some problems that cannot be solved well by using OOP. For example, how to extract the public method run of BVC and DVC?

class BVC: UIViewController {
    func run(){

class DVC: UITableViewController {
    func run(){
Swift -- Protocol oriented programming

  • Some OOP based solutions:
    -Put the run method into another object a, and then BVC and DVC have the attribute of object A: there are some additional dependencies
    -Add the run method to the uiviewcontroller category: uiviewcontroller will become more and more bloated and will affect all its other subclasses
    -Extract the run method to a new parent class and adopt multiple inheritance? (c + + supports multiple inheritance, OC does not support multiple inheritance): it will increase the complexity of program design and cause problems such as diamond inheritance, which need to be solved by developers
protocol Runnable {
    func run()
extension Runnable{
    func run()  {
class BVC: UIViewController,Runnable {}
class DVC: UITableViewController,Runnable{}

Precautions for Pop:

  • Priority is given to creating protocols rather than parent classes (base classes)
  • Priority value type(structenum), not reference type(class
  • Skillfully use the extended function of the protocolentension
  • Do not use protocols for protocol orientation