What is the difference between protocol, extension and category in IOS development? And how to use them appropriately?
Protocols
A protocol declares a programmatic interface that any class may choose to implement.
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. Protocols are like Interfaces, that provide some methods that the class conforming must implement.
Uses:
- A common use case is to let you alter the behavior of certain classes without the need to subclass them.
- Eg:
UITableViewDelegate
,UITableViewDataSource
Also see Protocol
Extension
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).
Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)
Uses:
Categories are a way to modularize a class by spreading its implementation over many files. Extensions provide similar functionality.
One of the most common uses of categories is to add methods to built-in data types like
NSString
orNSArray
. The advantage of this is that you don’t have to update existing code to use a new subclass
Extensions and Categories have some difference in Objective-C
Note: Following is true only for Objective-C
Categories allow you to add methods outside of the main interface file. Whereas Extensions must be implemented in main Interface file. Which means we can safely conclude you cannot use extensions for extending Builtin classes or Classes for which you don't have the source code, there you should use Categories. And to use extensions you need access to the source of the class you are extending.