Check out this example from the Swift docs on subscripts.
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
Usage example:
var matrix = Matrix(rows: 2, columns: 2)
matrix[1, 1] = 17
matrix[0, 1] = 11
print(matrix[1, 0]) //0.0
print(matrix) //Matrix(rows: 2, columns: 2, grid: [0.0, 11.0, 0.0, 17.0])
You can adjust this as needed for your specific use case.
It's not exactly a multidimensional array behind the scenes, but it acts like one for the user.
Oh, I forgot about this! While I haven't really used it, only watched the Developer video about it, there's Apple's new TabularData framework. I don't know if that would work for you, but it might be worth checking out.