Hey everyone,
This is my first time taking a crack at suggesting a feature for Swift, I hope some people would find this a compelling idea for an addition to Swift.
Problem
In many challenges of API Designs, you want your consumer to provide a way to get/set a specific concrete type.
Today, a consumer can express this idea by a Key Path, a wonderful concept in Swift. My consumer can tell me:
- This is how you can get a String from MyObject (
KeyPath
) - This is how you can mutate a String on MyObject (
WritableKeyPath
)
Commonly, though, you want to ask a consumer a different set of questions:
- Give me a way to retrieve a String on an arbitrary object
- Give me a way to mutate a String on an arbitrary object
While not caring what is the Root of that String, as long as you fulfil the concrete requirement.
Unfortunately, as of today there's no way to express a Key Path which isn't bound to a specific concrete Root.
Solution
I'd like to introduce a new type of KeyPath
— AnonymousKeyPath
. This key path does not care specifically what is the Root of the Keypath, but only the type of Value
constrained to it.
To shorten it, while a regular key path suggests:
KeyPath<A, B> = (A) -> B
An anonymous keypath suggests:
// e.g., give me a way to get a type B, I don't care what is the root
AnonymousKeyPath<B> = () -> B
Effect on source compatibility, ABI stability, and API resilience
I'm hoping this could be an entirely additive change, where you could provide a \Object.property
key path to an AnonymousKeyPath
which would be abstracted from the specific Root object.
Other options
Using a non-KeyPath to bridge the gap, e.g.
public struct AnonymousLens<T> {
public let get: () -> T
public let set: (T) -> Void
public init(get: @escaping @autoclosure () -> T,
set: @escaping (T) -> Void) {
self.get = get
self.set = set
}
}
Thank you for taking the time to read this :)