This episode is for subscribers only. To access it, and all past and future episodes, become a subscriber today!
See subscription optionsorLog inSign up for our weekly newsletter to be notified of new episodes, and unlock access to any subscriber-only episode of your choosing!
Sign up for free episodeWe 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!
👋 Hey there! Does this episode sound interesting? Well, then you may want to subscribe so that you get access to this episodes and more!
The Swift evolution review of the proposal to add a Result
type to the standard library. It discussed many functional facets of the Result
type, including which operators to include (including map
and flatMap
), and how they should be defined.
This talk explains a nice metaphor to understand how flatMap
unlocks stateless error handling.
When you build real world applications, you are not always on the “happy path”. You must deal with validation, logging, network and service errors, and other annoyances. How do you manage all this within a functional paradigm, when you can’t use exceptions, or do early returns, and when you have no stateful data?
This talk will demonstrate a common approach to this challenge, using a fun and easy-to-understand “railway oriented programming” analogy. You’ll come away with insight into a powerful technique that handles errors in an elegant way using a simple, self-documenting design.
Up until Swift 4.1 there was an additional flatMap
on sequences that we did not consider in this episode, but that’s because it doesn’t act quite like the normal flatMap
. Swift ended up deprecating the overload, and we discuss why this happened in a previous episode:
Swift 4.1 deprecated and renamed a particular overload of
flatMap
. What made thisflatMap
different from the others? We’ll explore this and how understanding that difference helps us explore generalizations of the operation to other structures and derive new, useful code!