I came from C# world, and used to arrays being reference types. As I understand, in swift arrays are value types, but they try to play as reference ones.
I don't actually know how to ask what I need (I think this is the case when I need to know answer to be able to ask question), but in C# I would say I need to store a reference to inner array of a jagged array into local variable.
Consider the following piece of code:
// a function to change row values in-place
func processRow(inout row : [Int], _ value : Int)
{
for col in 0..<row.count
{
row[col] = value;
}
}
// a function to change matrix values in-place
func processMatrix(inout matrix : [[Int]])
{
for rowIdx in 0..<matrix.count
{
// (1) Works with array in-place
processRow(&(matrix[rowIdx]), -1)
// (2) Creates local copy
var r = matrix[rowIdx]; // <--- What to write here to not make a copy but still have this local variable?
processRow(&r, -2);
}
}
var matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
processMatrix(&matrix)
print(matrix) // outputs [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
Swift sandbox here http://swiftlang.ng.bluemix.net/#/repl/8608824e18317e19b32113e1aa08deeb4ec5ab96ed8cdbe1dbfb4e753e87d528
Here I want to I process multidimensional array in-place, so that I don't create a copy of array or parts of array.
In option (1) I change everything to "-1", and it works, but is uses additional function for this.
In option (2) I try to use local variable to store matrix[rowIdx]
, but it actually creates a copy of inner array - not what I want; working with this variable changes copy of array, and not original one.
How can I achieve results like in option (1), but using local variable instead of function? That is, how can I obtain reference to inner array and put it to local variable?
I would understand answer "there's no way for this", but I want such answers to be accompanied by some Apple refs.