Here is one way to do it. Make an iterator out of your one dimensional array, and then use map
and compactMap
along with .next()
to replace the values of the twoDimArray
to create the newArray:
let oneDimArray = [1,2,3,4,5,6,7,8,9]
let twoDimArray = [[0,0,0], [0,0,0], [0,0,0]]
var iter = oneDimArray.makeIterator()
let newArray = twoDimArray.map { $0.compactMap { _ in iter.next() } }
print(newArray)
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
A nice feature of this technique is that you can easily fill in any pattern of array, and not just create a fixed 3x3 one for instance:
let oneDimArray = [1,2,3,4,5,6,7,8,9,10]
let patternArray = [[0], [0,0], [0,0,0], [0,0,0,0]]
var iter = oneDimArray.makeIterator()
let newArray = patternArray.map { $0.compactMap { _ in iter.next() } }
print(newArray)
Output
[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]
A generic function
We can turn this into a generic function that can replace the values of a 2D array with those of a 1D array. Note that the types of the values in the arrays can be different if you like:
func overlay<T, U>(_ array: [[T]], values: [U]) -> [[U]] {
var iter = values.makeIterator()
return array.map { $0.compactMap { _ in iter.next() }}
}
// Create an 2D array of strings from this pattern
let patternArray = [[0], [0,0], [0,0,0], [0,0,0,0]]
print(overlay(patternArray, values: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]))
Output
[["a"], ["b", "c"], ["d", "e", "f"], ["g", "h", "i", "j"]]