Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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!

like image 839
Ben Avatar asked Sep 10 '17 17:09

Ben


1 Answers

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)
like image 187
allenh Avatar answered Dec 29 '22 17:12

allenh