Keypath Forwarding

Hi,

I think Swift introduced a feature (in 5 or 5.1 or 5.2) that allowed the keypath to be forwarded. Keypath forwarding was the old name I think, some how I am not able to search for it.

If anyone has the link to the documentation (or an example) of the feature it would be great.

Thanks,
somu

Did you mean SE-0252 Key Path Member Lookup?

1 Like

@ddddxxx Thank you so much!!! was breaking my head over it

I didn't know it was built on top of @dynamicMemberLookup, every time I searched and found dynamicMemberLookup I dismissed it.

Based on my understanding:

  • Looks like @dynamicMemberLookup supports both String and Keypath.
  • When @dynamicMemberLookup is done via Keypath it is called Keypath Member Lookup

Example:

struct Car {
    var name: String
    var price: Int
}

@dynamicMemberLookup
struct Garage {
    var car : Car

    subscript<T>(dynamicMember keyPath: KeyPath<Car, T>) -> T {
        car[keyPath: keyPath]
    }
}

let c1 = Car(name: "aaa", price: 100)
let g1 = Garage(car: c1)
g1.name