We now know that flatMap
is an important operation that solves a common problem. Important enough for Swift to provide this operation for arrays and optionals in the standard library.
However, all of the types we define for our own problems and applications, the ones that the Swift standard library knows nothing about, all have this nesting problem. The Result
, Validated
, Func
, Parallel
type and more. Can we define flatMap
on them?
The answer is “yes we can and should be!” And as you define flatMap
it uncovers interesting semantics of your types. It also will show interesting connections with zip
, and that is what clarifies the purpose of the type. For example, why would you use Result
over Validated
? Why would you use Func
over Parallel
? It turns out that the way flatMap
and zip
relate to each other uncovers all of that.
So let’s define flatMap
on our own types and see what it teaches us!