Swift Language Arrays Lazily flattening a multidimensional Array with flatten()


We can use flatten() in order to lazily reduce the nesting of a multi-dimensional sequence.

For example, lazy flattening a 2D array into a 1D array:

// A 2D array of type [[Int]]
let array2D = [[1, 3], [4], [6, 8, 10], [11]]

// A FlattenBidirectionalCollection<[[Int]]>
let lazilyFlattenedArray = array2D.flatten()

print(lazilyFlattenedArray.contains(4)) // true

In the above example, flatten() will return a FlattenBidirectionalCollection, which will lazily apply the flattening of the array. Therefore contains(_:) will only require the first two nested arrays of array2D to be flattened – as it will short-circuit upon finding the desired element.