Size of arrays in MemoryLayout.size in Swift

Viewed 778

Sorry if the question may be duplicate I neither could find it here nor using Google.

I'm new to unsafe Swift and I was wondering why the size of an array of Bools which is e.g 10 bytes, is still 8 bytes ?

If I wasn't able to say what I meant I would be wondering if you could take a look at this code :

var boolArray = [Bool]()
for _ in 1...10{
    boolArray.append(true)
}
print(MemoryLayout.size(ofValue: boolArray))

I don't get why it prints 8 while the array has 10 bools which at least contains of 10 bytes.

2 Answers

That's because an Array itself don't really store anything - internally, they hold a reference to heap-allocated piece of memory, which really stores the data.

One of the reasons it's done this way is optimization - it allows the use of copy-on-write mechanism. Array is a struct, therefore it's a value type. However, the data it holds does not need to be copied every time you copy the Array - instead, multiple Arrays can point to the same area of memory, as long as they do not modify it.

Related