April 2017
Intermediate to advanced
316 pages
9h 33m
English
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 ...
Read now
Unlock full access