Join Károly Nyisztor for an in-depth discussion in this video Methods and class-bound protocols, part of Swift 4: Protocol-Oriented Programming.
- [Instructor] Protocols can also also provide instance and type message requirements. I add an instance method called update. It takes an argument called data of type data. And it returns a boolean. I also add a static method called increment counter. This method is supposed to implement the internal counter property. If we define a requirement for a method that modifies the instance, it is recommended to mark it with the mutated keyword.
Since the update method is probably going to modify the instance, let's mark it at mutating. The mutating keyword allows value types to also adopt the protocol. Now if you want to restrict conforming types to classes only, we can define the protocol as such by making it inherit from the any object protocol. Now we get the compiler error because of the mutating keyword. Class methods can always modify the class, thus we don't need to use the mutating keyword in class use.
We should enforce reference semantics only if protocol requirements should not be fulfilled by a value types. I removed the restriction we just added and the compiler error is gone. Protocols can provide requirements for specific intializers too. I'm going to implement and intializer which takes two arguments. And argument called tag of type string, that is going to initialize our tag property. And an argument called data of type data.
That initializes our data property. The signature is the same as when declaring former initializes in a type, except that we don't provide the implementation.
- 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