How does Swift know the address of an element in an array of Any?

How does Swift know the address of an element in an array of Any? I can’t find any explanation. For example:

var array: [Any] = [0, "1"]
print(array[1]) // print “1”

I’m wondering how does Swift implement accessing an array of heterogenous types. Usually, in other programming languages like C/C++, we can only declare an array of a specified type, therefore we can calculate the address of an element by: start + index * Element.size . How to calculate the address of an element of array with a specified index if we don't have a fixed size of elements in the array?

The type erased Any has a fixed layout of size 32 on 64b and 16 on 32b which contains enough information to recover the original type and value. If I were to write this out in C/C++:

struct Any {
  size_t data[3];
  const void *type;
};

So in this case, an array of Any is simply an array of that structure as it's single element type. Swift's print does some reflection when it encounters this Any type to print the actual value within it. Also, keep in mind that array's elements may not always be contiguous, so if you want to access its contiguous memory I would suggest using: withContiguousStorageIfAvailable.

7 Likes

Thanks! It explains a lot. And I find more information here: swift/TypeLayout.rst at main · apple/swift · GitHub

1 Like
Terms of Service

Privacy Policy

Cookie Policy