来自字符串的 Swift Keypath [英] Swift Keypath from String

查看:36
本文介绍了来自字符串的 Swift Keypath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to create a Keypath from a String in Swift 4 to access a value in a struct by its path or variable name

最后我发现我应该使用 CodingKeys 而不是 KeyPaths通过字符串访问结构变量的 a 值

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)

这篇关于来自字符串的 Swift Keypath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆