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

后端 未结 10 1120
鱼传尺愫
鱼传尺愫 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:21

    From the official documentation of the Swift language:

    Note that the array is not copied when you set a new value with subscript syntax, because setting a single value with subscript syntax does not have the potential to change the array’s length. However, if you append a new item to array, you do modify the array’s length. This prompts Swift to create a new copy of the array at the point that you append the new value. Henceforth, a is a separate, independent copy of the array.....

    Read the whole section Assignment and Copy Behavior for Arrays in this documentation. You will find that when you do replace a range of items in the array then the array takes a copy of itself for all items.

提交回复
热议问题