O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The flatMap method

flatMap is a generic instance method for any type that conforms to Sequence protocol. It can be used to flatten one level of a dimension of a sequence or to remove nil values in the sequence. The following example presents a two-dimensional array, in other words, nested arrays.

Calling flatMap on this array reduces one dimension and flattens it so the resulting array becomes [1, 3, 5, 2, 4, 6]:

let twoDimArray = [[1, 3, 5], [2, 4, 6]] let oneDimArray = twoDimArray.flatMap { $0 } 

In this example, flatMap returns an array containing the concatenated results of the mapping transform over itself. We can achieve the same result by calling joined on our array and then map, as follows:

 let oneDimArray = twoDimArray.joined().map ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required