Friday, January 26, 2018

Swift’s Reflective Underpinnings

Joe Groff (via Helge Heß):

People tend to think of static typing and Reflection as being diametrically opposed. But ultimately, I think we can come up with designs that marry the best aspects of both. Providing the expressivity and power of Reflection while still preserving the static reasoning capabilities of the type system.

[…]

When we cast to a protocol type, the runtime consults this table and searches for the implementation of that protocol if there is one. So using this technique, we can ask the same questions that we asked in Objective-C. “Do you respond to this method and if so, please respond.” And we can factor this out into a generic function, allowing us to avoid hard coding a particular responder protocol and use any protocol in our system as an action for responders to respond to.

[…]

The good news is that the runtime is fairly well set up to support this kind of query. Even though the implementation isn’t yet there in the standard library. Those type meta data objects that I talked about for Structs, Enums, and Classes, have a reference to what’s called the nominal type descriptor. And this contains fairly detailed information about the original definition of the type. It includes its name, it includes the module or parent type it was nested in, and it includes a fairly detailed account of its layout as well.

[…]

Swifts type system was carefully designed to support either specialization or runtime dynamic dispatch with the same source code. And no matter what implementation you use, you get type safety from the compiler.

So I wonder whether we could do the same thing for reflecting over the shapes of types.

See also: SE-0195: Introduce User-defined “Dynamic Member Lookup” Types.

Comments RSS · Twitter

Leave a Comment