Efficient way of flat mapping a range of a multidimensional random access collection
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.