Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyPath to Nested Class

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!

like image 490
Michael_mhr Avatar asked Oct 27 '25 04:10

Michael_mhr


1 Answers

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

like image 87
CRD Avatar answered Oct 30 '25 16:10

CRD