简体   繁体   中英

Is it possible to get the KVC-String from Swift 4 KeyPath?

For a project I am currently working on, it would be very useful to get the KVC-String from a KeyPath instance my method is receiving. Short 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 might seem not very useful, but in my project it is :) I found a property on KeyPath called _kvcKeyPathString which is also public, but it returns nil every time I tried. Or is their maybe a possibility to use reflection there? Thanks in advance for ideas/solutions!

I don't know of a pure Swift way to get the name of the property as a string yet.

But, if you add the @objc attribute to the property then _kvcKeyPathString will actually have a value instead of always being nil. Also, since Swift structs can't be represented in Objective-C, this method only works for classes.

A minimal working example usage:

class SomeClass {
    @objc var someProperty = 5
}

let keyPath = \SomeClass.someProperty
print(keyPath._kvcKeyPathString)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM