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?