Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reflection of deep nested object #20

Open
mapo80 opened this issue Dec 17, 2018 · 2 comments
Open

Reflection of deep nested object #20

mapo80 opened this issue Dec 17, 2018 · 2 comments

Comments

@mapo80
Copy link

mapo80 commented Dec 17, 2018

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)

@bradhilton
Copy link
Member

bradhilton commented Dec 18, 2018

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]

@mapo80
Copy link
Author

mapo80 commented Dec 18, 2018

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(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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants