I’m reading the documentation and I am constantly shaking my head at some of the design decisions of the language. But the thing that really got me puzzled is how arrays are handled.
I rushed to the playground and tried these out. You can try them too. So the first example:
var a = [1, 2, 3]
var b = a
a[1] = 42
a
b
Here a
and b
are both [1, 42, 3]
, which I can accept. Arrays are referenced – OK!
Now see this example:
var c = [1, 2, 3]
var d = c
c.append(42)
c
d
c
is [1, 2, 3, 42]
BUT d
is [1, 2, 3]
. That is, d
saw the change in the last example but doesn’t see it in this one. The documentation says that’s because the length changed.
Now, how about this one:
var e = [1, 2, 3]
var f = e
e[0..2] = [4, 5]
e
f
e
is [4, 5, 3]
, which is cool. It’s nice to have a multi-index replacement, but f
STILL doesn’t see the change even though the length has not changed.
So to sum it up, common references to an array see changes if you change 1 element, but if you change multiple elements or append items, a copy is made.
This seems like a very poor design to me. Am I right in thinking this? Is there a reason I don’t see why arrays should act like this?
EDIT: Arrays have changed and now have value semantics. Much more sane!