0

I found some really strange behavior in Swift. Here's the code:

var array2d: [[Int]] = [[1]]
print(array2d) // prints [[1]]

var first = array2d[0]
first.append(2)

print(array2d) // still prints [[1]]!!!

I would totally expect the last line to print [[1, 2]]. I can't explain the current behavior. I'd expect array2d[0] to return a reference to the first item, or possibly a copy of that reference. In either case, modifying that object should modify array2d. But that's not what's happening.

If, however, I update the array like this:

array2d[0].append(2)

it then prints [[1, 2]], as expected.

Can someone please explain this for me?

TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76

1 Answers1

1

How arrays are referenced/passed around/copied in swift is a point of a lot of contention, take a look at this link.

In essence what is happening is that var first = array2d[0] is taking a copy of the array at that index as opposed to creating a reference as you were expecting. Hence accessing the array with the subscript notation allows to you to correctly alter the array but creating a new variable doesn't.

Blake Lockley
  • 2,931
  • 1
  • 17
  • 30