@dynamicMemberLookup keyPaths not working with generic classes?

I've added dynamicMemberLookup keypath support to a generic class in hopes of achieving forwarding to the underlying type. This compiles and runs, and seems like it will work:

open class BaseClass<GenericType> {
    public var child: GenericType!

    subscript<T>(dynamicMember keyPath: KeyPath<GenericType, T>) -> T {
        return child[keyPath: keyPath]

    // ... impl omitted

public protocol Specialization: AnyObject {
    var prop1: String { get }
    var prop2: String { get }

public final class SubClass: BaseClass<Specialization> {
    // ... impl omitted

While the above compiles, I am unable to use dynamicMemberLookup to proxy through to var child as I'd expect. This doesn't compile:

let sub: SubClass<Specialization> = // ... impl omitted
print(sub.child.prop1) // ok
print(sub.prop1) // ERROR: Use of unresolved identifier

This should work, right?

Which version of Swift are you using?

I have a different error:

let sub: SubClass<Specialization> = SubClass() // error: Cannot specialize non-generic type 'SubClass'
print(sub.child.prop1) // no error
print(sub.prop1) // no error

Replacing let sub: SubClass<Specialization> = SubClass() with let sub: SubClass = SubClass() makes it compile alright.

It turns out Xcode just wasn't give me the most pertinent error which would've identified the issue immediately. It was saying

Use of unresolved identifier

instead of saying

'subscript' is inaccessible due to 'internal' protection level


Terms of Service

Privacy Policy

Cookie Policy