Swift protocol-oriented programming summary

Swift protocol-oriented programming

The so-called protocol-oriented programming is to use the protocoldeclaration method, and then use to extensionprovide the default implementation. As long as the class that needs to use the method follows this protocol, you can directly use the extensionimplementation.

 

protocol animal {
    var food: String {get}
    func eat()
}

extension animal {
    func eat() {
        print("food name is \(food)")
    }
}

struct Cat: animal {
    
    var food: String = "mouse"
}

struct Dog:animal {
    var food: String = "cat"
}

let cat = Cat()
let dog = Dog()
cat.eat()
dog.eat()

log:
food name is mouse
food name is cat

Code reuse

  • Inheritance : It will bring coupling.
    • The cost of inheritance: This is not a novel topic. It has been controversial since the birth of object-oriented programming. We often have to endure more and more complicated and huge inheritance systems to obtain code reusability, and with inheritance levels With the increase, the complexity of the code will accelerate, and the subsequent bugs will become more and more difficult to find. At this time, we may need to rely on design patterns to find our way back. However, most design patterns can only help you straighten out your code structure, but at the same time further deepen the complexity of your code.
  • category/extension : Will pollute all classes
  • Protocol-oriented programming : protocol+ extensionMinimize coupling

Benefits of protocol-oriented programming

The advantage of protocol-oriented programming is that by implementing a function through protocol + extension, you can define the necessary and sufficient conditions, no more, no less. This minimizes coupling . Users can freely combine these protocols like building blocks and write one classor structto complete complex functions. In fact, Swift's standard library is almost everything is starting out as a protocol.

Why is Swift a protocol-oriented programming language?

Because it Swiftis more recommended to use value type variables ( struct) rather than reference type ( class) variables, Swiftmany common data types, strings, collection types, and structures and enumerations are value types rather than reference types. Value types are Variables will automatically perform a low-consumption value copy when assigning values. Compared with objects, it copyis more efficient and does not have thread safety issues.

Why do we need struct

structAnd classthe main differences:

  • structIs a reference value, and classis the type of reference
  • structThere is no inherited function, classthere is inherited function

The difference between the two basic levels of struct and class reflects the difference from the Objective-C language. The swift language has brought about a whole new and earth-shaking change.

Let me talk about the first difference. From the perspective swiftof updates and structcontinuous improvement, Apple recommends using structit instead class, because the difference between structvalue reference and classtype reference ensures that the use of structcoding can write more secure and reliable code. Why do you say this? The classtype reference points the variable to the same memory address when assigning a value. This will bring some unexpected problems over a long span. Imagine a simple example, viewControllerAholding an NSMutableArrayarray mutalbeArray, which contains 100 userpieces of information will be mutableArrayassigned at this time viewControllerB. For this viewControllerB, it only needs the first 10 userpieces of information, so it mutableArraydeletes the redundant information. Such a brain-dead operation leads to viewControllerAmodule display errors and potential logic errors. The use of structvalue references does not cause such problems.

The second difference is that structthere is no inherited function. This is because swiftin essence it is a protocol-oriented Protocol Orientedlanguage. structThere is no and no inherited function. In order to realize a certain function, structit is enough to obey and implement a certain protocol. From a higher level, they struct+protocolare swiftthe two cornerstones of a protocol-oriented language.

to sum up

Swift is a language that supports multiple programming paradigms. It supports object-oriented programming, protocol-oriented programming, and functional programming. In the project development process, the controller and view parts should adopt more object-oriented programming methods due to the use of system frameworks; while the custom type parts such as models or business logic should be given priority to protocol-oriented programming.

Reference article

Swift protocol-oriented programming (with code)

Talk about Swift protocol-oriented programming

Let's start with protocol-oriented programming in Swift

A Preliminary Study of Protocol-Oriented Programming in Swift



Author: Yu Yi Suoyan
link: https: //www.jianshu.com/p/d0a5b92a1dd5

Guess you like

Origin blog.csdn.net/fzhlee/article/details/107931866