Can I get a KVC string from Swift 4 KeyPath?

For the project I'm currently working on, it would be very useful to get a KVC-String from the KeyPath instance that gets my method. A brief example:

struct Person { var name: String } let propertyCache = ["name": "something"] func method<T>(_ keypath: KeyPath<Person, T>) -> T? { let kvcName = keypath.kvc return propertyCache[kvcName] } 

This may not seem very useful, but in my project it :) I found a property in KeyPath with the name _kvcKeyPathString , which is also public, but with each repetition it returns nil . Or could it be an opportunity to use reflection there? Thanks in advance for your ideas / solutions!

+4
swift
source share
1 answer

I don’t know about the pure Swift way to get the property name as a string.

But if you add the @objc attribute to the property, then _kvcKeyPathString will actually have a value, and not always be zero.

+4
source share

All Articles