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

Chris Lattner sabre at nondot.org
Mon Nov 20 20:03:34 CST 2017

On Nov 15, 2017, at 8:35 PM, Paul Cantrell via swift-evolution <swift-evolution at swift.org> wrote:
> Interesting! I like the spirit of this proposal a lot.
> One question: presumably this behaves like Ruby’s method_missing in that any natively implemented members shadow the dynamic ones? i.e. Swift looks for a static match first, then uses the dynamicMember only as a fallback?

Right.  I added that to the proposal in the “API resilience section”.

> Q: It seems like this fundamentally alters Swift’s aesthetic of “either an operation is type-safe, or it’s clear at the point of use that it’s not.”  Should this use an operator other than a period, e.g. `pickle->loads(blob)`?

AnyObject dispatch is the closest relative to this feature that Swift currently has, and is neither type safe nor unsurprising. :-)

It is important to note that implementations of this protocol can definitely implement it in terms of optionals, so it is completely type safe.  Consider a JSON implementation for example: the dynamic getter would return a type of “JSON?”.  That design is fully type safe.

> Q: Why the open-ended `associatedtype DynamicMemberLookupValue`? Seems like it will always just be Self in practice.
> A: It would be Self in the Python and JSON examples in the proposal, but making it an associatedtype adds no implementation burden, does no apparent harm, and adds flexibility. Shifting types on traversal could be particularly useful in creating DSLs (e.g. sepia → Genus, sepia.officinalis → Species).

Not necessarily the same.  Consider a bad use of this for sugaring a string to int dictionary.  The string “keys” would be the “dynamicMember", but the DynamicMemberLookupValue would be the key type: Int. 

> Q: Is there any special handling for that member name string — to handle ruby method names like `blank?`, for example?

A: Use the standard Swift backquote mechanism:   x.`blank?`()

> Q: Should the subscript also take arg types and/or labels to allow overloading?
> A: Ruby, Python, and JS all resolve members by name alone, and leave it to functions to untangle their own args. Obj-C is the lone oddball here. Relying on the companion proposal to handle the args makes sense.

AFAIK, Swift’s subscript model is already general enough to do what we need it to do, but if there is some interesting language that isn’t served by it, we can talk about that when it comes up.


More information about the swift-evolution mailing list