What is Protocol Oriented Programming in Swift? What added value does it bring?

前端 未结 5 962
耶瑟儿~
耶瑟儿~ 2020-12-02 13:41

From Apple\'s own website: \"At the heart of Swift\'s design are two incredibly powerful ideas: protocol-oriented programming and first class value semantic

5条回答
  •  天命终不由人
    2020-12-02 13:56

    It surprised me that none of the answers mentioned value type in POP.

    To understand what is protocol oriented programming, you need to understand what are drawbacks of objected oriented programming.

    1. It (Objc) has only one inheritance. If we have very complicated hierarchy of inheritance, the bottom class may have a lot of unnecessary state to hold.
    2. It uses class which is a reference type. Reference type may cause code unsafe. e.g. Processing collection of reference types while they are being modified.

    While in protocol oriented programming in swift:

    1. It can conform multiple protocols.
    2. It can be used by not only class, but also structures and enumerations.
    3. It has protocol extension which gives us common functionality to all types that conforms to a protocol.
    4. It prefers to use value type instead of reference type. Have a look at the standard swift library here, you can find majority of types are structures which is value type. But this doesn't mean you don't use class at all, in some situation, you have to use class.

    So protocol oriented programming is nothing but just an another programming paradigm that try to solve the OOP drawbacks.

提交回复
热议问题