如何在 swiftui 的运行时通过名称作为字符串访问 Struct 属性

how to acess Struct property by name as a string in runtime in swiftui

我有 JSON 回复

 result: 
        [
            Result(date: "2022-04-24", abc: 1463, def: 0, ghi: 0.0), 
            Result(date: "2022-04-25", abc: 1451, def: 0, ghi: 0.0), 
            Result(date: "2022-04-26", abc: 24838, def: 100, ghi: 25.0), 
            Result(date: "2022-04-27", abc: 72833, def: 461, ghi: 115.25), 
            Result(date: "2022-04-28", abc: 31881, def: 0, ghi: 0.0), 
            Result(date: "2022-04-29", abc: 18706, def: 0, ghi: 0.0)
        ], 

,现在在我的代码中我正在使用选择器并且必须动态更改密钥

**example--->** 
result.abc,
result.def,
result.ghi

我必须动态更改的代码

HStack{
            
ForEach(downloads.indices, id: \.self){ index in
                
                if index == downloads.count-1 {
                    
                    Text("\(downloads[index].abc)")
                        .font(.largeTitle.bold())
                        .foregroundColor(.white)
    
                    
                }
                
                
            }
        }
        .frame(maxWidth: .infinity, alignment: .leading)

你可以在上面的代码中看到

downloads[index].**abc**

取而代之,我需要更改 def 和 ghi,但动态地

在我调用上面文件的主视图中

@State var selectedScreen: [String] = ["abc","def", "ghi"]
BarGraph(downloads: dataservice.statsdetails, value: selectedScreen[pickerSelectedItem])

但是如果我将它作为字符串动态传递,它会给我错误

  [1]: https://i.stack.imgur.com/l6kna.png

你能帮我解决这个问题吗

一种直接的方法是向您的结构添加一个函数,该函数 returns 给定键的正确值。

func stringProperty(for path: String) -> String {
    switch path {
    case "abc":
        return "\(abc)"
    case "def":
        return "\(def)"
    case "ghi":
        return "\(ghi)"
    default:
        fatalError("Unknown property name")
    }
}