Auto protocol conformance if Key Path Member Lookup meets protocol requirement

With Key Path Member Lookup, the compiler knows that certain properties could be provided by this subscript function with known types. We can even see this types of properties in code completion.

However, the compiler does not treat this as a proper protocol conformance. Please refer the code below:

protocol P {
    var property: Bool { get }

struct MyValue {
    let property = "Sample property"

struct S: P {
    let value = MyValue()
    subscript<T>(dynamicMember member: KeyPath<MyValue, T>) -> T  {
        value[keyPath: member]

The compiler will complain Type 'S' does not conform to protocol 'P'. Is it possible to let compiler add protocol conformance automatically for this case and treat it as valid code?

1 Like

Thanks for pointing out the original discussion thread. Conceptually they indeed come from different world. But if it happens that we have to have these two in the code, it seems redundant though.

As mentioned at the bottom of that thread, it seems likely we'd want to reconsider that point now that there's KeyPath-based dynamicMemberLookup, which didn't exist when Chris made his original post. Given that the KeyPath version allows compile time verification of the protocol requirements, it seems at least some of the original objections may no longer apply. It does, however, raise ergonomic issues around how to tell uses that the property requirements of a protocol can be met automatically by a KeyPath while functional requirements must still be bridged manually.

Terms of Service

Privacy Policy

Cookie Policy