Efficient way of flat mapping a range of a multidimensional random access collection I've recently answered a question about reading elements from an array of arrays. A way it could be interpreted is that the OP wanted to read a range that could span over multiple subarrays of the 2D array like so :

let a = [["5", "3", ".", ".", "7", "."],
         ["6", ".", ".", "1", "9", "5"]]

a.lazy.flatMap{$0}[1..&lt;7] ["3", ".", ".", "7", ".", "6"]


This way of reading a range would need to at least flatMap all the previous arrays to the lower bound of the range. Which would be wasteful.

A more natural way would be to only read the needed elements from the original array:

func get&lt;T&gt;(_ range: Range&lt;Int&gt;, from array2d: [[T]]) -&gt; [T]? {
    var result: [T] = []
    result.reserveCapacity(range.upperBound - range.lowerBound)

    var count1 = 0

    //Get the index of the first element
    guard var low = array2d
            .firstIndex(where: {
                 count1 += $0.count
                 return range.lowerBound &lt; count1 }),
          count1 != 0
    else { return nil }

    let before = count1 - array2d[low].count
    var count2 = before

    //Get the index of the last element in the range
    guard let high = array2d[low..&lt;array2d.endIndex]
            .firstIndex(where: {
                 count2 += $0.count
                 return range.upperBound &lt;= count2
            }),
          count2 != 0
    else { return nil }

    //Append the elements in the array with the low index
    for i in (range.lowerBound - before)..&lt;min(range.upperBound - before, array2d[low].count) { 
        result.append(array2d[low][i]) 
    }

    //If the range spans over multiple arrays
    if count1 &lt; count2 {
        low += 1

        //Append the elements in the arrays with an index between low and high
        while low &lt; high {
            result.append(contentsOf: array2d[low])
            low += 1
        }

        //Append the elements in the array with the high index
        for i in 0..&lt;(range.upperBound - count2 + array2d[high].count) {
            result.append(array2d[high][i])
        }
    }

    return result
}


Which could be used like so :

let a = [["0", "1", "2", "3", "4", "5"], ["6", "7"], [], ["8","9","10","11", "12"], ["13","14", "15"]]

get(5..&lt;11, from: a) //Optional(["5", "6", "7", "8", "9", "10"])
get(7..&lt;9, from: a) //Optional(["7", "8"])


To me, the above code feels.. on the border of sanity/maintainability...

What I'd like to do is to make it more generic, maybe as an extension to RandomAccessCollection, and making the flattening process recursive for arrays/collections of arbitrary dimensions. I'm stuck here and not sure if this is the appropriate network to ask such a question.

Feedback on all aspects of the code is welcome, such as (but not limited to):


Efficiency,
Readability,
Naming.
I gather that your intent was to write a method that iterates through an array of arrays (but avoiding functional patterns), flattening the results in the process such that given...

let a = [["0", "1", "2", "3", "4", "5"], ["6", "7"], [], ["8","9","10","11", "12"], ["13","14", "15"]]


... that result for 5..&lt;10 would be ["5", "6", "7", "8", "9"]

Assuming that’s what you were trying to do, I think you can simplify it:

extension Array {
    func flattened&lt;T&gt;(range: Range&lt;Int&gt;) -&gt; [T]? where Element == Array&lt;T&gt; {
        var result: [T] = []

        var offset = range.startIndex
        var length = range.upperBound - range.lowerBound

        result.reserveCapacity(length)

        for subarray in self {
            let subarrayCount = subarray.count
            if offset &lt; subarrayCount {
                if length &gt; subarrayCount - offset {
                    result += subarray[offset...]
                    length -= subarrayCount - offset
                } else {
                    return result + subarray[offset..&lt;offset + length]
                }
            }
            offset = Swift.max(0, offset - subarrayCount)
        }

        return nil
    }
}


In terms of observations on your code:


I wouldn’t advise get method name. It’s not very meaningful name and only conjures up confusion with getters. I’d go with something that captured the “flattening” nature of the routine.
As a general rule, we should avoid closures with side-effects in functional programming patterns. Even though you’ve written an “iterative” rendition of the OP’s code, you’re using a functional method, firstIndex, and you are updating variables outside the closure. It’s technically allowed but is contrary to the spirit of functional programming patterns and is dependent upon the implementation details of firstIndex.