Extending your protocols with default behavior

The previous examples have mainly used variables as the requirements for protocols. One slight downside of protocols is that they can result in a bit of code duplication. For example, every object that is HerbivoreType has a favoriteMeat variable. This means that you have to duplicate this variable in every object that conforms to HerbivoreType. Usually, you want as little code repetition as possible, and repeating a variable over and over again might seem like a step backward.

Even though it's nice if you don't have to declare the same property over and over again, there's a certain danger in not doing this. If your app grows to a large size, you won't remember every class, subclass, and superclass ...

Get Mastering iOS 12 Programming - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.