Chapter 8. Putting the pro in protocol-oriented programming

 

This chapter covers

  • The relationship and trade-offs between generics and using protocols as types
  • Understanding associated types
  • Passing around protocols with associated types
  • Storing and constraining protocols with associated types
  • Simplifying your API with protocol inheritance

Protocols bring a lot of power and flexibility to your code. Some might say it’s Swift’s flagship feature, especially since Apple markets Swift as a protocol-oriented-programming language. But as lovely as protocols are, they can become difficult fast. Plenty of subtleties are involved, such as using protocols at runtime or compile time, and constraining protocols with associated types.

This chapter’s goal is to lay down a solid foundation regarding protocols; it will shed light on using protocols as an interface versus using protocols to constrain generics. This chapter also aims to carry you over the hump of what can be considered advanced protocols, which are protocols with associated types. The end goal is to make sure you understand why, when, and how to apply protocols (and generics) in multiple scenarios. The only requirements are that you’re at least a little bit familiar with protocols and that you have read chapter 7, “Generics.” After this chapter, protocols and associated types will repeatedly return, so I recommend not to skip this one!

8.1. Runtime versus compile time

8.2. The why of associated types

8.3. Passing protocols with associated types

8.4. Closing thoughts

Summary

Answers