Chapter 7. Generics

 

This chapter covers

  • How and when to write generic code
  • Understanding how to reason about generics
  • Constraining generics with one or more protocols
  • Making use of the Equatable, Comparable, and Hashable protocols
  • Creating highly reusable types
  • Understanding how subclasses work with generics

Generics are a core component of Swift, and they can be tricky to understand at first. There is no shame if you’ve been staying away from generics, perhaps because they are sometimes intimidating or confusing. Like a carpenter can do work without a hammer, so can you develop software without generics. But making generics part of your regular software routine sure does help, because by using generics you can create code that works on current and future requirements, and it saves much repetition. By using generics, your code ends up more succinct, hard-hitting, boilerplate-reducing, and future-proof.

This chapter starts by looking at the benefits of generics and when and how to apply them. It starts slow, but then ramps up the difficulty by looking at more complex use cases. Generics are a cornerstone of Swift, so it’s good to internalize them because they’re going to pop up a lot, both in the book and while reading and writing Swift out in the wild.

After enough exposure and “aha” moments, you’ll start to feel comfortable in using generics to write hard-hitting, highly reusable code.

7.1. The benefits of generics

7.2. Constraining generics

7.3. Multiple constraints

7.4. Creating a generic type

7.5. Generics and subtypes

7.6. Closing thoughts

Summary

Answers