Reflection in later versions of Swift language

I obviously think there should be large modifications to the reflection API in the Swift library, unlike other languages, reflection in Swift is yet incomplete which I think will be great for both the language and the developers at large.

1 Like

I would also totally love to see better introspection possibilities in swift. I remember toying around the runtime metadata for types, and there’s actually a decent amount of information stored there, but no way to really access it easily.

(Ps I moved this topic out of Proposal Reviews and into Discussion)

But just to further the discussion so that it doesn’t die (which is might anyway,) what kind of changes would you like to see? Personally I would like to see an API that makes it easy to work with the runtime metadata for types. You can access them currently by some very hacky stuff where you do some unsafeBitCast magic to access it.

Here’s a very small example showing how you can see the kind of entity the type is:

let type: Any.Type = Optional<String>.self
let pMetadata = unsafeBitCast(type, to: UnsafePointer<Int>.self)
print(pMetadata[0])

This is very brittle and would break if the layout of the metadata ever changed. So it would be nice to have a way to expose the information on the metadata. @Joe_Groff helped us a little with the offset to fields for structs, but it would be nice to get more of that kind of info.

Part of the goal of ABI stability is to also stabilize the core parts of these reflection data structures, since they’re now used by the Swift runtime to implement the Mirror type, and are increasingly used by other tools like lldb and Apple’s memory debugging tools like leaks to understand Swift programs at runtime. While there are still changes planned before Swift 5, after that point we should be able to guarantee at least some parts of metadata layout as ABI. A nice effect of this would be that it’d allow third-party libraries to experiment with exposing Swift reflection info without waiting on the Swift standard library itself to design the proper long-term functionality.

17 Likes

I would love to see a way to add extra reflection metadata to properties or functions similar to how Go does:

type User struct {
    FirstName string `json:”first_name”`
}