2

I'm trying to convert a `struct1 to Realm objects right now. Realm object has same keypath with original struct. so If I can get all writable keypaths from original struct, it is possible to convert with general method.

public protocol KeyPathListable {
    var allKeyPaths:[WritableKeyPath<Self, Any>]  { get }
}

extension KeyPathListable {
    private subscript(checkedMirrorDescendant key: String) -> Any {
        return Mirror(reflecting: self).descendant(key)!
    }
    var allKeyPaths:[WritableKeyPath<Self, Any>] {
        var membersTokeyPaths = [WritableKeyPath<Self,Any>]()
        let mirror = Mirror(reflecting: self)
        
        for case (let key?, _) in mirror.children {
            if let keyPath = \Self.[checkedMirrorDescendant: key] as? WritableKeyPath<Self, Any> {
                membersTokeyPaths.append(keyPath)
            }
        }
        return membersTokeyPaths
    }
}

Just found the code snippet above but it returns KeyPath(not WritableKeyPath). I tried to typecast in this case, but it returns nil. Maybe mirror function has problem. Is there any solution for that?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Free Bird
  • 71
  • 1
  • 5
  • 3
    That `allKeyPaths` solution is never going to work. You cannot store a `KeyPath` as `KeyPath` because [generic types in Swift are invariant](https://stackoverflow.com/questions/41976844/swift-generic-coercion-misunderstanding). – Dávid Pásztor Aug 05 '21 at 14:21
  • this is not that issue. it is getting all keypaths correctly. but not writable keypath. not sure is there method to convert keypath to writable keypath. I'm going to save struct to the realm in watch kit. watch kit don't support Runtime pod. so can't use unrealm pod right now. so trying to implment manually. please think you have massive struct. have to convert all element to realm object. it's really bored work. so wanna do this with keypath. – Free Bird Aug 05 '21 at 15:22
  • my idea is just define protocol called Realmable. it will has type alias to get Realm Object Type and public init function and managedObject function to convert current struct to the realm object. if all struct has writable keypath and realm object has same keypath in raw value, we can make an another protocol keypathable and then implement over two functions in extension with generic. – Free Bird Aug 05 '21 at 15:31
  • Why go into all this hassle when you could just make your types Realm compatible in the first place? – Dávid Pásztor Aug 05 '21 at 15:39

0 Answers0