If you've been around a Swift developer long enough, you must have heard them mention protocol-oriented programming at least once. This programming paradigm was introduced by Apple at WWDC 2015 in a talk that generated a lot of buzz among developers. Suddenly, we learned that thinking in classes and hierarchies leads to code that's hard to maintain, change, and expand. The talk introduced a method of programming that is focused on what an object can do instead of explicitly caring about what an object is.
This chapter will demonstrate to you how you can make use of the powers of POP, and it will show you why it's an important feature of Swift. We'll start off with some simple use cases, and then we'll take a deep dive into its associated types and generic protocols.
Understanding these design patterns and recognizing situations in which a protocol, protocol extension, or a generic protocol can help you improve your code will lead to code that is not only easier to maintain but also a joy to work with. The structure for this chapter is as follows:
- Defining your own protocols
- Checking for traits, not types
- Extending your protocols with default behavior
- Improving your protocols with associated types
By the end of this chapter, you might feel a bit overwhelmed and amazed. Don't worry, shifting your mindset from OOP to a Protocol-Oriented approach isn't easy by any means. It's an entirely different way of thinking about structuring your code that will take some getting used to. It's time to dive right in by defining some of your own protocols.