Protocols stand at the core of POP. Learn what a protocol is and how to create a protocol, define some property and method requirements, and create a type that adheres to this protocol.
- [Nar] Protocols stand at the core of POP. A protocol models extraction by describing what the conforming types shall implement. This means, protocols serve as blueprints rather than defining actual functionality. Protocols are types so their names must begin with a capital letter. As we can see on swift.org here, Apple has clear recommendations regarding protocol naming. Protocols that describe what something is, should read as nouns, for example, collection. Protocols that describe a capability should be named using the suffixes -able, -ible, or -ing.
For example, equatable, Progressreporting, and so on. Let's get started exploring the protocol syntax. I start by defining a protocol called BinaryRepresentable. We provide the property and method requirements between the curly brackets that follow the protocol name. We specify variables as usual. This protocol has a property called tag of type string. We're going to get an error here.
Properties in the protocol need to have at least a getter. The tag property is both acceptable and gettable. That is, read/write. We specify this by writing get set after this declaration. I declare another property called data. It is of type data and it's only gettable. That is, read only. Note that we can't declare constants using the let key word.
To define an immutable property, declare it as var and use the get specifier. Also, default values and computed property definitions are not allowed in the protocol. Since we only define the properties in the protocol without assigning default values to them, Swift's start inference engine has no way of working out the type, therefore, we must always specify the type of our properties in the protocol. In a protocol, we can define type property requirements using the static keyword.
Let's declare a static property called counter of type integer. And it's read-only as well. This counter property, since it's static, stores a value that is shared by all instances.
- Comparing object-oriented programming with protocol-oriented programming
- Methods and class-bound protocols
- Adopting a protocol
- Declaring asynchronous behavior
- Preparing and implementing fallback logic
- Implementing an app using protocol-oriented programming