改变ArraySlice会实例化一个新的数组实例吗? [英] Would mutating an ArraySlice instantiate a new array instance?

查看:146
本文介绍了改变ArraySlice会实例化一个新的数组实例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var absences = [0, 2, 0, 4, 0, 3, 1, 0]
let midpoint = absences.count / 2

var firstHalf = absences.prefix(upTo: midpoint)
let secondHalf = absences.suffix(from: midpoint)

Apple的报价:

firstHalf切片和secondHalf切片都不分配自己的任何新存储.取而代之的是,每个视图都显示了失踪数组的存储视图.

Neither the firstHalf nor secondHalf slices allocate any new storage of their own. Instead, each presents a view onto the storage of the absences array.

当我尝试如下更改firstHalf时:

firstHalf[1] = 19

firstHalf的值发生变化,但原始数组absences保持不变(firstHalf[1]等于19,而absences[1]等于2) 那么在后台发生了什么.我是否通过更改数组切片来实例化新数组? 预先感谢.

the values of firstHalf changes but the original array absences remains the same (firstHalf[1] is equal to 19 while absences[1] equals to 2) So what happens in the background. Did I instantiate a new array by mutating the array slice? Thanks in advance.

推荐答案

是的,标准库的集合类型(包括ArrayArraySlice)都具有写时复制行为.这意味着他们可以与其他集合共享其元素的存储,直到它们被突变为止,在这种情况下,他们将获得他们自己的副本.

Yes, the standard library's collection types, including Array and ArraySlice, all have copy-on-write behaviour. This means that they can share storage of their elements with other collections until they are mutated, in which case they will take their own copy of them.

在您的情况下,切片firstHalf可以查看的基础数组缓冲区是非唯一引用的(因为absencessecondHalf都可以查看).因此,当您使firstHalf变异时,将触发一个副本–创建一个包含切片元素(但不一定是 entire 数组)的 new 缓冲区.

In your case, the underlying array buffer that the slice firstHalf has a view onto is non-uniquely referenced (as both absences & secondHalf also have a view onto it). Therefore when you go to mutate firstHalf, a copy is triggered – creating a new buffer containing the elements of the slice (but not necessarily the entire array).

firstHalf现在在此新缓冲区上具有唯一的视图,其中absences& secondHalf都共享对旧数组缓冲区的视图.因此,firstHalf现在可以在不影响原始数组元素的情况下更改其缓冲区的元素,从而保留值的语义.

firstHalf now has a unique view onto this new buffer, with absences & secondHalf both sharing a view onto the old array buffer. Therefore firstHalf can now mutate the elements of its buffer without affecting the elements of the original array, thus preserving value semantics.

这篇关于改变ArraySlice会实例化一个新的数组实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆