flatMap and Swift 1.2 Betas 2 and 3
And at this point, hopefully it’s clear that
flatMap
and optional chaining do very similar things. Optional chaining essentially is a compact version offlatMap
that only works on methods. When you want the same functionality as optional chaining, but instead with a function you need to pass the optional value into (like withfind
) instead of calling a method on that value, you needflatMap
.That’s not all
flatMap
does – it’s also a method on arrays (think of a mapping function that turns elements into arrays of elements), and there’s a generic free function version that works on sequences and collections.