Is there a reason that Swift array assignment is inconsistent (neither a reference nor a deep copy)?

10/14 08:34
阅读数 0

问题:

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. 这里ab都是[1, 42, 3] ,我可以接受。 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] . c[1, 2, 3, 42] 1,2,3,42 [1, 2, 3, 42]但是d[1, 2, 3] That is, d saw the change in the last example but doesn't see it in this one. 也就是说, d看到了最后一个例子中的变化,但是在这个例子中看不到它。 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. e[4, 5, 3] ,很酷。 It's nice to have a multi-index replacement, but f STILL doesn't see the change even though the length has not changed. 有一个多索引替换是很好的,但即使长度没有改变, f STILL也看不到变化。

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. 总而言之,如果更改1个元素,则对数组的常见引用会看到更改,但如果更改多个元素或附加项目,则会生成副本。

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! 更加理智!


解决方案:

参考一: https://en.stackoom.com/question/1d2ZN
参考二: https://stackoom.com/question/1d2ZN
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部