Chapter 10. Understanding map, flatMap, and compactMap
This chapter covers
- Mapping over arrays, dictionaries, and other collections
- When and how to map over optionals
- How and why to flatMap over collections
- Using flatMap on optionals
- Chaining and short-circuiting computations
- How to mix map and flatMap for advanced transformations
Modern languages like Swift borrow many concepts from the functional programming world, and map and flatMap are powerful examples of that. Sooner or later in your Swift career, you’ll run into (or write) code that applies map and flatMap operations on arrays, dictionaries, and even optionals. With map and flatMap, you can write hard-hitting, succinct code that is immutable—and therefore safer. Moreover, since version 4.1, Swift introduces compactMap, which is another refreshing operation that helps you perform effective transformations on optionals inside collections.
In fact, you may even be familiar with applying map and flatMap now and then in your code. This chapter takes a deep dive to show how you can apply map and flatMap in many ways. Also, it compares these operations against alternatives and looks at the trade-offs that come with them, so you’ll know exactly how to decide between a functional programming style or an imperative style.
This chapter flows well after reading chapter 9. If you haven’t read it yet, I recommend going back to that chapter before reading this one.