Chapter 13. Swift patterns

 

This chapter covers

  • Mocking types with protocols and associated types
  • Understanding conditional conformance and its benefits
  • Applying conditional conformance with custom protocols and types
  • Discovering shortcomings that come with protocols
  • Understanding type erasure
  • Using alternatives to protocols

In this chapter, you’re going to see some useful patterns that you can apply in your Swift programming. I made sure that these patterns were more Swift-focused, as opposed to a more-traditional OOP focus. We’re focusing on Swift patterns, so protocols and generics take center stage.

First, you’re going to mock existing types with protocols. You’ll see how to replace a networking API with a fake offline one, and also replace this networking API with one that’s focused on testing. I throw in a little trick related to associated types that will help you mock types, including ones from other frameworks.

Conditional conformance is a powerful feature that allows you to extend types with a protocol, but only under certain conditions. You’ll see how to extend existing types with conditional conformance, even if these types have associated types. Then, you’ll go a bit further and create a generic type, which you’ll power up as well by using conditional conformance.

13.1. Dependency injection

13.2. Conditional conformance

13.3. Dealing with protocol shortcomings

13.4. An alternative to protocols

13.5. Closing thoughts

Summary

Answers