Writing Flexible Code with Protocols and Generics

If you spend enough time around a Swift developer, you'll hear them mention protocol-oriented programming. Apple introduced this programming paradigm 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, modify, and expand. The talk introduced a way of programming that is focused on what an object can do instead of explicitly caring about what an object is.

This chapter is packed with complex and interesting information that is essential if you want to write beautiful Swift code.  You will learn how you can make use of the powers of POP, and it will show you why it's an essential feature of Swift. You'll start off with some simple use cases, and then you'll take a deep dive into its associated types and generic protocols.

Understanding 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. Don't worry, shifting your mindset from classical OOP to a protocol-oriented approach isn't easy. It's an entirely different way of thinking about structuring your code, which will take some getting used to. It's time to dive right in by defining some of your own protocols.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset