This chapter is from the book

Optional Mapping

Swift’s map and flatMap functions enable you to conditionally apply functions to optional values. Their calls are similar, as you see in the following declarations, and both are incredibly useful tools:

The map closures return type U, which may or may not be an optional, while flatMap closures specifically return type U?, which is always an optional. This practical limitation simply means you can use map with closures that return non-optionals, but you cannot do the same with flatMap:

Both the mapping and if-let include about the same level of code complexity for this particular example. Both unwrap the optional returned by UIImage(named:) and then print the size. You can argue which approach is better. Both bind the unwrapped result to a local constant whether that constant does or does not have an explicit name.

Filtering nil Values with flatMap

The flatMap function offers great utility both in the realm of optionals and outside it. With optionals, you can use flatMap to filter away nil values and easily convert an array of optionals to an array of unwrapped values: