How Mirror Works

Swift places a lot of emphasis on static typing, but it also supports rich metadata about types, which allows code to inspect and manipulate arbitrary values at runtime. This is exposed to Swift programmers through the Mirror API. One might wonder, how does something like Mirror work in a language with so much emphasis on static types? Let’s take a look!

swift.org/blog/how-mirror-works/

Swift provides runtime type inspection through the Mirror API. This allows developers to examine arbitrary values and traverse object graphs without prior knowledge of types at compile time.

The API uses a mix of Swift and C++ code to access metadata, with custom implementations for tuples, structs, classes, and enums to retrieve children and properties. CustomReflectable enables types like Array and Dictionary to offer tailored representations. While internals may change until ABI stability, this setup supports dynamic features in a statically typed language.


Category:

Tag:

Year: