Zewo / Reflection

DEPRECATED
MIT License
599 stars 46 forks source link

Reflection of deep nested object #20

Open mapo80 opened 5 years ago

mapo80 commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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!