What is a Protocol?
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol itself doesn't provide an implementation—it simply says 'anything that wants to be X must be able to do Y.' As an Architect, you use protocols to achieve Dependency Inversion, allowing your high-level logic to depend on abstractions rather than concrete implementations.
- Defining and Conforming to Protocols
You define a protocol using the protocol keyword. Any class, struct, or enum can then 'conform' to it by providing the required implementation. This is exactly like 'implements' in Dart.
- Protocol Extensions (The Secret Sauce)
The real power of Swift protocols comes from Extensions. You can provide a 'default implementation' for a protocol method. Any type that conforms to the protocol will automatically inherit that behavior. This is Swift's way of doing 'Mixins' without the complexity of multiple inheritance.
- Delegation Pattern
In iOS development, protocols are the foundation of the Delegation Pattern. It allows one object to hand off (delegate) responsibilities to another. For example, a 'NetworkManager' might delegate the handling of an error to a UI component via a protocol.
Protocols vs. Inheritance
| Feature | Class Inheritance | Protocols |
|---|---|---|
| Type Support | Classes only | Structs, Classes, and Enums |
| Flexibility | Rigid 'Is-A' relationship | Flexible 'Acts-As' relationship |
| Multiplicity | Single inheritance only | Multiple protocol conformance |
| Coupling | Tightly coupled to parent | Loosely coupled / Decoupled |
| Initial State | Can store data | Cannot store data (properties only) |