swift4 - 来自字符串的 Swift Keypath

标签 swift4 keypaths

有没有办法在 Swift 4 中从字符串创建 Keypath,以通过路径或变量名访问结构中的值

Finally I found out that I should use CodingKeys instead of KeyPaths to access the a value of a variable of a struct by String

提前致谢, 迈克尔

最佳答案

考虑一下你有这样的东西,

struct foo {

var test: doo

}

struct doo {

var test: Int

}
 //How to use it 

    let doo = Doo(test: 10)
    let foo = Foo(test: doo)

    let mykeyPath = \Foo.test.test

    let result = foo[keyPath: mykeyPath]

    print(result)

关于swift4 - 来自字符串的 Swift Keypath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52427304/

相关文章:

swift - 在泛型函数 where 子句中使用 Self 时出错

ios - 使用 Storyboard "UIViewController-ZWG-5q-24I"中的标识符 "Main"实例化 View Controller ,但没有获得 UITableView。

swift - 当命令无法执行时 NSTask 得到通知 "command not found"

swift - 如何将 AnyKeyPath 转换为 WritableKeyPath?

swift - 如何根据一对多关系中第一项的键路径对 Realm 结果进行排序?

Swift 泛型、约束和 KeyPaths

generics - 在 Swift 4 中,当键路径和值的类型是通用的但相同时,如何分配给键路径?

Swift 4 SKLabelNode 没有出现

ios - 带有 UIButtons 的 Swift Keypath

Swift keyPath 与协议(protocol)