Swift 内存中的数组实例

Swift array instances in Memory

现在我正在看 WWDC,了解 Swift 表演环节

那个环节一张图看得我一头雾水

我知道数组在编译时无法确定它的大小,所以他们将项目实例存储在堆中,并将该项目的引用存储在堆栈中,如上所示(d[0], d[1])

但是那个数组中的 refCount 是什么(在 d[0] 旁边)?

drawables数组实例的变量指针吗?

数组是 struct,因此是一种值类型。但是,有一些写时复制优化,这可能是这个refCount.

的原因

documentation for Array 中,它指出:

Arrays, like all variable-size collections in the standard library, use copy-on-write optimization. Multiple copies of an array share the same storage until you modify one of the copies. When that happens, the array being modified replaces its storage with a uniquely owned copy of itself, which is then modified in place. Optimizations are sometimes applied that can reduce the amount of copying.

还举了个例子:

In the example below, a numbers array is created along with two copies that share the same storage. When the original numbers array is modified, it makes a unique copy of its storage before making the modification. Further modifications to numbers are made in place, while the two copies continue to share the original storage.

var numbers = [1, 2, 3, 4, 5]
var firstCopy = numbers
var secondCopy = numbers

// The storage for 'numbers' is copied here
numbers[0] = 100
numbers[1] = 200
numbers[2] = 300
// 'numbers' is [100, 200, 300, 4, 5]
// 'firstCopy' and 'secondCopy' are [1, 2, 3, 4, 5]

所以在数组变异之前,数组的存储是共享的。这就是为什么它需要计算引用,而不是释放一个仍然可能被另一个变量使用的数组。