how can I create a KeyPath from a nested class? I don't know how to access the nested class using Backslash.
Example Code:
class Config {
var clients: Array<Client> = [Client()]
// Nested Class
class Client {
public var name: String = "SomeName"
}
}
var conf = Config()
func accessValue<T, U>(
_ keyPath: ReferenceWritableKeyPath<Config, Array<T>>,
valuePath: ReferenceWritableKeyPath<T ,U>) -> Any {
let member: Array<T> = conf[keyPath: keyPath]
let firstMember: T = member.first!
let value = firstMember[keyPath: valuePath]
return value
}
// How should I call this function?
print(accessValue(\Config.clients, valuePath: wanna_know))
// Should print "SomeName"
Thanks in advance!
A nested class is referred to by name using standard dot notation, so in your case the nested class is Config.Client
.
As you know a key-path is of the form \<type name>.<path>
so the path you are seeking is \Config.Client.name
.
HTH