Protocol — The power of Swift
Part-3 — Protocol composition
Updated on 14th July 2018, 12:45 PM GMT 5:30+
Welcome to the 3rd part of this series, In-case you missed first or second part, I will strongly suggest you that first coverup the essential concepts from
“Part-1: What is type-casting and class-types?”
“Part-2 — confirming a protocol”
After completing part-1 and part-2,
Now you are ready with essential skills to understand this blog.I ended part-2 with unanswered question, now it’s time to answer your question
What is protocol composition?
Combining multiple protocols as a group and giving them a single name is know as protocol composition. This is handy when you needs to confirm same group of protocols many times in your project like UICollectionViewDelegate and UICollectionViewDatasource.
Protocol composition does not create new protocol,
It generates a new name using typealias, which is equivalent to two or more protocols specified by you, during typealias.
What is protocol combination | protocol Inheritance?
Creating a new protocol by inheriting one or more protocol is known as protocol combination or you can say protocol inheritance. You can also achieve the same result as protocol composition by creating empty protocol which will be inherited from multiple protocols you want to combine.
Question: Which is a better way, “Protocol composition” or “Protocol combination”, when I should use the first one and when other one?
Nice question, Both approaches have their own pros and cons, let me explain this step by step.
- Protocol composition
- In this approach you can’t add new method signatures, you can only use the methods which are available for protocols that you are compositing together.
- This will not create a new datatype, so compiler will have less load during compilation.
Less Datatype, compiler will have less task to perform during compilation process. It will increase the average compilation time of your code. - The class or structure which will confirm this composited protocol will only have two additional datatypes which are UITableViewDataSource and UITableViewDelegate, as per above example “ProtocolExample4.swift”.
2. Protocol combination | Protocol inheritance
- In this approach you are creating new protocol means you are creating new datatype as well, in this protocol you can add as many new method signature you want.
- But keep in mind that here you are creating new datatype as well, it will increase the load for compilation tasks for your compiler.
- The class or structure which will confirm this combined or inherited protocol will have three additional datatypes,
UITableViewDataSource and UITableViewDelegate and HSCombineTableViewDatasourceDelegate the protocol its self, as per above example “ProtocolExample5.swift”.
Now it’s time to update “my rule of thumb for possible class types”.
Better I name it “Rule of thumb for possible data types”.
To be Continue…
Part-4 — My rule of thumb for possible data types