Getting String representation of Swift ReferenceWritableKeyPath is failed (returns pointer instead of type)

I have a Product class inherited from Realm Object:

@objc class Product: Object {
    @Persisted(primaryKey: true) var id: String = ""
    @Persisted var externalId: String?
    @Persisted var name: String?
}

I try to write a universal method for objects update which takes dictionary with keyPaths and values and update object with this Realm method:

func setValue(_ value: Any?, forKey key: String)

This is a computed variable for getting String representation of KeyPath:

fileprivate extension KeyPath {
    var asString: String {
        let wholeString = String(describing: self)
        let dropLeading =  "\\" + String(describing: Root.self) + "."
        let keyPathString = "\(wholeString.dropFirst(dropLeading.count))"
        return keyPathString
    }
}

And it's perfectly works during debug mode, but when I build an app with Release scheme instead of "Product.name" it returns something like "\Product.<computed 0x000000010c51ed18 (Bool)> and the app crashed trying to set value for this keypath.

If anyone has idea how to fix this, it would be really appreciated.

There is, unhappily, no current way to get the string representation of a key path.

Using String(describing:) gets the key path's description, and as you've seen this is not a reliable way of getting the path. Even if it worked in release mode right now, it could break at any time in the future.

I suggest you continue discussing this over in the Swift forums (forums.swift.org). Extra visibility of the issue might help to get a solution a bit sooner.

Getting String representation of Swift ReferenceWritableKeyPath is failed (returns pointer instead of type)
 
 
Q