What's the best practice when creating a 2-dimensional array in Swift?
My newbie approach to Swift is:
let list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
let foobar = [[Int]]()
let row = -1
let (index, data) in list.enumerated() {
if index % 3 == 0 {
row += 1
foobar.append([])
}
foobar[row].append(data)
}
Thought about a more elegant approach but the accumulated property is immutable and .reduce
wouldn't work:
let x = list.reduce([]) { (acc, val) -> [[Int]] in
if acc.count % 3 == 0 {
acc.append([])
}
acc[acc.count].append(contentsOf: [val])
}
So, just wondering how people approach this in Swift,
Thanks!