Reflection icon indicating copy to clipboard operation
Reflection copied to clipboard

Reflection of deep nested object

Open mapo80 opened this issue 7 years ago • 2 comments

I have a complex classes of this type

`public class Info: Codable {

public var user: UserModel?
public var data: String?

}

public struct UserModel: Codable { public var username: String? public var name: String?
}`

I want to access sub properties in this way "user.info", is it possibile?

var obj = Info() let xxx: String? = try? get("user.info", from: obj)

mapo80 avatar Dec 17 '18 19:12 mapo80

Sorry, this isn't supported. If you know what the object type is, like in this example, you could always use key paths:

let obj = Info()
let xxx = obj[keyPath: \.user?.info]

bradhilton avatar Dec 18 '18 15:12 bradhilton

Thanks for your answer, but object type it's not known.

Since objects are of codable type, I have performed the serialization of the object into Dictionary and from this I have retrieved the value through Keypath.

` public func valueForKeyPath<T>(keyPath: String) -> T? { var keys = keyPath.components(separatedBy: ".") guard let first = keys.first as? Key else { print("Unable to use string as key on type: (Key.self)"); return nil } guard let value = self[first] else { return nil } keys.remove(at: 0) if !keys.isEmpty, let subDict = value as? [NSObject:AnyObject] { let rejoined = keys.joined(separator: ".")

        return subDict.valueForKeyPath(keyPath: rejoined)
    }
    return value as? T
}

`

I think this is not the best approach for performance!

mapo80 avatar Dec 18 '18 15:12 mapo80