BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

The flatMap() method transforms optionals and arrays

Available from Swift 1.2

Paul Hudson      @twostraws

The flatMap() method is designed to allow you to transform optionals and elements inside a collection while also decreasing the amount of containment that happens. For example, if you transform an optional in a way that will also return an optional, using map() would give you an optional optional (a double optional), whereas flatMap() is able to combine those two optionals into a single optional.

let lengthOfFirst = names.first.flatMap { count($0) }

Decreasing the amount of containment also makes flatMap() a simple way of converting multi-dimensional arrays into single-dimensional arrays:

[[1, 2], [3, 4], [5, 6]].flatMap { $0 }

There is no "map" operation there, so we're just left with the flattening behavior – that will result in a single array containing the value [1, 2, 3, 4, 5, 6].

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 1.2…

Download all Swift 1.2 changes as a playground Link to Swift 1.2 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.