Ben
Ben

Reputation: 3485

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!

Upvotes: 8

Views: 3870

Answers (1)

allenh
allenh

Reputation: 6622

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)

Upvotes: 13

Related Questions