An Introduction to Protocol Oriented Programming in Swift
swift面向协议编程的根本原因在于值类型的存在;面向对象必须要有引用类型的支持;
Protocol Oriented approach was introduced to resolve some issues in programming and it also differs in various scenarios when compared to Object-Oriented programming. So let’s dive into the topic.
What is Protocol Oriented Programming?
Protocols basically serve as a blueprint like classes rather than a fully functional types for methods, properties, and other requirements. This is done to perform a piece of functionality and behaves like an interface and tells what to implement. It is a powerful feature of Swift language. Apple tells us:
“Don’t Start with the Class, Start with the Protocol”
Why We Need POP?
When we design any software system, then we figure out the general requirements that satisfy the given system. We, even model the relationship b/w the UI elements such as buttons, view, images etc. for which we generally start with superclass and model the relationships using inheritance.
In Swift, as we have the concept of POP so, we can even start with protocols and can model the relationships as protocol implementations. In the protocol oriented approach, we model our system with a protocol, rely on the concepts like:
- Protocol Extensions
- Protocol Inheritance
- Protocol Composition
In Swift, we use structs, enums, and tuples rather than working only with classes since, Value Semantics are preferred over Reference Types.
Also, there could be various cases where OOP is not the best solution to implement. Let’s check and figure out the drawbacks in Object-Oriented concept. We know that Inheritance is one of the most important concepts in OOP but, inheritance doesn’t work for value types and modern languages like Swift prohibits to support the feature of multiple inheritances due to complexities and value types is the first citizen of Swift. So, POP does a great job by providing the ability to add multiple abilities to the class, struct, and enum with protocols and extensions that supports multiple implementations while we code.
Other benefits with Protocol implementations are:
- Swift checks whether the requirements of the protocol are full-filled or not for the classes we are implementing at compile-time, so, this helps us to find out if there were any issues or bugs in code even before we ran our program.
- Also, protocols bring more abstraction mechanism than classes do in Swift.
- We’re not restricted to only use classes since any type, including value types, can implement a protocol.
- A type can implement multiple protocols.
- We can create as many protocols as we need.
Before I talk about POP in detail and how to use and implement it, we must understand the basics right, so let us focus on Swift Types first. Here is the diagrammatic representation of Swift Types that we have.
Well, here I am interested in the behavior of Classes and Structure, one belongs to the reference type and other to value type and observe how objects behave through an example.
And, this is really important to understand and why is it so? If you have a very complex hierarchy and you set something in one part of the code, it should not have any wrong consequences in the other part. So, the lesson is:
- Classes use reference i.e if you set something to other it is not a copy instead it is a reference.
- Whereas, in value type such as structures, passes things as a copy, not as a reference.
Conclusion
Apple, always recommends going with the value type while we program in Swift. Structures are preferable when we have a small copy of data and it is much safer than having multiple references to the same objects in our code. The concept becomes more important when we talk about variable and passing their value. In Swift, we work in a multi-threaded environment and if we have copies of variable then, we don’t need to worry about them in the other place where value may get change. So, using structure is advised by Apple and Protocol-Oriented Programming serves better abstraction with structures.
Using Protocols and it’s extensions features, we can really ignore/avoid for making a huge superclass and then inheriting functionality from there. So, Hope it is now clear to you what is POP and why Apple use this.
Note: This does not mean that we don’t use Class, there are some situations where classes are the only option left for our implementation.
In the other part of this article, we will see how to implement and use protocols, protocol extensions, Generics with the protocol.
https://www.technotification.com/2018/08/protocol-oriented-programming-swift.html
相关文章
- 创建couchbase的bucket 提示RAM不够用 all the ram in the cluster is already allocated to existing bucekets,delete some buckets,,
- How to open .dbml in designer mode with VS?
- error CS8773: "Feature 'global using directive' is not available in C# 9.0" after downgrade from net6.0 to net5.0
- How to get ASCII value of string in C#
- Does it make sense to put antiforgerytoken in _Layout.cshtml?
- How To: Configure MachineKey in ASP.NET 2.0
- How To Display Variable Value In View?
- 第147章 SQL函数 TO_TIMESTAMP
- OpenCV 程序报错 The application has requested the Runtime to terminate it in an unusual way.
- Can't connect to X11 window server using 的问题,求解
- Connect to DB2 database in eclipse via jdbc
- angular ng-bind-html异常Attempting to use an unsafe value in a safe context处理
- apt-get install报错E: Failed to fetch问题解决
- is not allowed to connect to this mysql server
- mysql更新字段值提示You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode
- There is no type initializer in Swift----One answer is to use static, it is the same as class final.
- vue-cli · Failed to download repo vuejs-templates/webpack: self signed certificate in certificate ch
- Android Call to ‘Thread.sleep()‘ in a loop, probably busy-waiting Inspection info:
- 从致远软件到致远互联,见证to B产业的时代交接
- pat 1092 To Buy or Not to Buy(20 分)
- [已解决]报错Could not install packages due to an EnvironmentError
- 解决Fatal error in launcher: Unable to create process using '"'
- macOS 安装mtr 和mtr: Failure to start mtr-packet: Invalid argument 错误的解决
- [LeetCode] 1000. Minimum Cost to Merge Stones 混合石子的最小花费
- Convert PLY to VTK Using PCL 1.6.0 or PCL 1.8.0 使用PCL库将PLY格式转为VTK格式
- Ten ways to improve the performance of large tables in MySQL--转载
- 5 Ways to Use Log Data to Analyze System Performance--reference
- C# DataTable To Entities
- 《GKT:Efficient and Robust 2D-to-BEV Representation Learning via Geometry-guided Kernel Transformer》
- Blocks to Cubes