嵌套类的KeyPath

时间:2018-11-03 11:58:08

标签: swift4 keypaths

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

示例代码:

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"

谢谢!

1 个答案:

答案 0 :(得分:1)

嵌套类是使用标准的点符号命名的,因此在您的情况下,嵌套类为Config.Client

您知道密钥路径的格式为\<type name>.<path>,因此您要查找的路径为\Config.Client.name

HTH