We can use [flatten()](<http://swiftdoc.org/v2.2/protocol/SequenceType/#func-generator-element_-sequencetype-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](<http://swiftdoc.org/v2.2/type/FlattenBidirectionalCollection/>)
, which will lazily apply the flattening of the array. Therefore [contains(_:)](<http://swiftdoc.org/v2.2/protocol/SequenceType/#func-generator-element_-equatable-contains_>)
will only require the first two nested arrays of array2D
to be flattened – as it will short-circuit upon finding the desired element.