[swift-evolution] [Pitch] Introduce User-defined "Dynamic Member Lookup" Types

Brent Royal-Gordon brent at architechies.com
Fri Nov 17 03:02:03 CST 2017


> On Nov 16, 2017, at 10:08 PM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
> 
> So, let me sketch a vague idea of how this might work. This is definitely not fully baked, but it might give you an idea.

Looking at this again, I realize I accidentally generated a giant wall of text. tl;dr:

* There is no protocol; this is done through an ad-hoc mechanism to allow overloading.

* Use `subscript(additionalProperty:)` to dynamically create a property. The parameter type can be any of:

	* An arbitrary type: compiler will look for static constants (including no-payload cases) of the type accepted by the parameter, and treat them as valid properties of `Self`.
	* A `KeyPath` type: compiler will look for properties on the KeyPath's Root type and treat them as valid properties of `Self`.
	* An `ExpressibleByStringLiteral` type: compiler will treat any identifier as a valid property.

* Use `subscript(additionalMethod:)` to dynamically create methods. The subscript returns a closure which is already bound to `self`, but not to the parameters. The parameter type can be any of:

	* An arbitrary type: compiler will look for static methods (including cases) returning the type accepted by the parameter and whose parameters are all metatypes, and will treat them as valid methods of `Self` (after transforming all metatypes into plain types).
	* A `(Foo) -> (ParamList) -> ReturnValue` type (i.e. an unbound method): Compiler will treat all instance methods of `Foo` as valid methods of `Self`.
	* An `ExpressibleByStringLiteral` type: compiler will treat any identifier as a valid method (and will pass both the base name and argument labels in a single string).

* The string literal forms cover use cases where you want to accept anything and sort it out at runtime. The keypath/unbound method forms cover use cases where you're echoing the interface of an underlying type. The arbitrary type forms cover use cases where you want to create members based on compact tables of information.

tl;dr for the tl;dr: I think we can cover a ton of use cases for automatically "creating" properties and methods using minor variations on a single mechanism which only vaguely resembles this one.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list