Wednesday, February 8, 2023

Swift Proposal: Custom Reflection Metadata

SE-0385 (discussion):

In Swift, declarations are annotated with attributes to opt into both built-in language features (e.g. @available) and library functionality (e.g. @RegexComponentBuilder). This proposal introduces the ability to attach library-defined reflection metadata to declarations using custom attributes, which can then be queried by the library to opt client code into library functionality.


Registering code to be discovered by a framework is a common pattern across Swift programs. For example, a program that uses a plugin architecture commonly uses a protocol for the interface of the plugin, which is then implemented on concrete types in clients. This pattern imposes error-prone registration boilerplate, where clients must explicitly supply a list of concrete plugin types or explicitly register individual plugin types to be used by the framework before the framework needs them.


To support advanced schema customization, the [Realm] property wrapper could store a string that provides a custom name for the underlying database column, specified in the attribute arguments, e.g. @Persisted(named: "CustomName"). However, storing this metadata in the property wrapper requires additional storage for each instance of the containing type, even though the metadata value is fixed for the declaration the property wrapper is attached to. In addition to higher memory overload, the metadata values are evaluated eagerly, and for each instantiation of the containing type, rendering property-wrapper instance metadata too expensive for this use case.

Comments RSS · Twitter · Mastodon

Leave a Comment