The Swift Runtime: Class Metadata Initialization
Summary
But nothing stops me from writing the wrong type in that case, which is where these helpers come in: The use of key paths enforces that the “cast” is actually to a “base class” or “subclass” in the embedding hierarchy, which is a lot safer than going to UnsafeRawPointer and back explicitly (which is what I was doing before I added these). The simplest way to address this would be to put in an “accessor function” that takes generic arguments and returns the appropriate superclass (probably by calling somewhere in its implementation), and have subclasses reference that. In the real Swift codebase, the demangler—the code to take a mangled name and reconstruct its structure—is written in C++, which allows it to be used in the runtime, the compiler, the command-line tool, and the out-of-process inspection library used by the debugger. Fortunately, the name mangling scheme used by the compiler had an escape hatch: a way to embed a pointer to the simple “accessor function” that I mentioned at the beginning of this section. (In theory I could remove this extra bit of indirection by pointing directly to the accessor function, since it’s no longer serving a purpose, but in practice that would probably mean changing a lot more in the compiler, and that wasn’t worth the effort.)