Chapter 12. Protocol extensions

 

This chapter covers

  • Flexibly modeling data with protocols instead of subclasses
  • Adding default behavior with protocol extensions
  • Extending regular types with protocols
  • Working with protocol inheritance and default implementations
  • Applying protocol composition for highly flexible code
  • Showing how Swift prioritizes method calls
  • Extending types containing associated types
  • Extending vital protocols, such as Sequence and Collection

Previous chapters have shown how to work with protocols, associated types, and generics. To improve your abstract protocol game, this chapter sheds some light on protocol extensions. To some, being able to extend a protocol is the most significant feature of Swift, as you’ll see later in this chapter.

Besides declaring a method signature, with protocols you can supply full implementations. Extending a protocol means that you can offer default implementations to a protocol so that types don’t have to implement certain methods. The benefits are profound. You can elegantly bypass rigid subclassing structures and end up with highly reusable, flexible code in your applications.

In its purest form, a protocol extension sounds simple. Offer a default implementation and be on your merry way. Moreover, protocol extensions can be easy to grasp if you stay at the surface. But as you progress through this chapter, you’ll discover many different use cases, pitfalls, best practices, and tricks related to correctly extending protocols.

12.1. Class inheritance vs. Protocol inheritance

12.2. Protocol inheritance vs. Protocol composition

12.3. Overriding priorities

12.4. Extending in two directions

12.5. Extending with associated types

12.6. Extending with concrete constraints

12.7. Extending Sequence

12.8. Closing thoughts

Summary

Answers

sitemap