嵌套的 KeyPath Class

KeyPath to Nested Class

如何从嵌套的 class 创建 KeyPath?我不知道如何使用反斜杠访问嵌套的 class。

示例代码:

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"

提前致谢!

嵌套的 class 使用标准点符号按名称引用,因此在您的情况下,嵌套的 class 是 Config.Client

如您所知,关键路径的形式为 \<type name>.<path>,因此您正在寻找的路径是 \Config.Client.name

HTH