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

后端 未结 10 1128
鱼传尺愫
鱼传尺愫 2020-12-07 08:12

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 a

10条回答
  •  鱼传尺愫
    2020-12-07 08:42

    Delphi's strings and arrays had the exact same "feature". When you looked at the implementation, it made sense.

    Each variable is a pointer to dynamic memory. That memory contains a reference count followed by the data in the array. So you can easily change a value in the array without copying the whole array or changing any pointers. If you want to resize the array, you have to allocate more memory. In that case the current variable will point to the newly allocated memory. But you can't easily track down all of the other variables that pointed to the original array, so you leave them alone.

    Of course, it wouldn't be hard to make a more consistent implementation. If you wanted all variables to see a resize, do this: Each variable is a pointer to a container stored in dynamic memory. The container holds exactly two things, a reference count and pointer to the actual array data. The array data is stored in a separate block of dynamic memory. Now there is only one pointer to the array data, so you can easily resize that, and all variables will see the change.

提交回复
热议问题