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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So in other words, it makes a deep copy of everything?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.