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

Michel Fortin michel.fortin at michelf.ca
Thu Nov 16 06:51:33 CST 2017


Key paths could be made to work by implementing the protocol in terms of retrieving key paths instead:

protocol SupplementalKeyPathDispatching {
	associatedType KP: PartialKeyPath<Self>
	static func supplementalKeyPath(for name: String) -> KP
}

and in your implementation of PyVal:

extension PyVal: SupplementalKeyPathDispatching {
	static func supplementalKeyPath(for name: String) -> KeyPath<PyVal, PyVal> {
		return \PyVal[dynamicMember: name]
	}
}

The compiler then implements two transforms:

	\PyVal.add_trick
	// becomes:
	PyVal.supplementalKeyPath(for: "add_trick")
	// returns key path \PyVal[dynamicMember: name]

and:

	let Dog = Python.import(“DogModule.Dog")
	let dog = Dog("Briana")

	dog.add_trick("snore")
	// becomes:
	dog[keyPath: \PyVal.add_trick]("snore")
	// or fully expanded:
	dog[keyPath: PyVal.supplementalKeypath(for: "add_trick")]("snore")
	// calls dog[dynamicMember: name]

You now have one more level of indirection which allows key paths. There's no compile time checking however: all imaginable key paths will work.

> Le 16 nov. 2017 à 1:00, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> * Actually, for that matter, let's talk about key paths. In principle, you can already think of member lookup in Swift—or at least property and subscript lookup—as though it always worked by constructing a key path and using `subscript(keyPath:)` to access it. Is there some way we could model this feature as extending the set of keys available on a given type—perhaps in a way that allowed compile-time-limited and strongly-typed sets of keys, like I mention with the `UIAppearance` example, in addition to the open-ended, type-erased sets you need—and then looking things up by key path? (Sorry if this is a little vague—I know very little about how key paths are implemented.)
> 

-- 
Michel Fortin
https://michelf.ca

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171116/5a83f22b/attachment.html>


More information about the swift-evolution mailing list