How is Any implemented?

I am trying to understand how the Any type is implemented, but I cannot find any information about it (e.g. searching for "swift string implementation" leads to String.swift from the standard library and one can find StringGuts.swift from there, but nothing turns up for "Any", partly because it is such a generic word.)

  1. How is Any implemented? I assume it is a struct with at least a pointer to the actual value. Is there source code available for the implementation (similar to String)?

  2. Where is the type information stored? Is it stored on the struct or behind some pointers?

  3. How does assigning a value type to Any work in terms of memory management? Is the value copied to the heap?

Thank you!

I had a response on another thread explaining the struct layout of it here: How does Swift know the address of an element in an array of Any? - #2 by Alejandro

If the value can be stored within 3 words, then it's stored inline the Any struct, otherwise Any stores a pointer to some heap object. The type information is simply a pointer to the metadata. If you have more questions, let me know!

3 Likes