Home > Back-end >  how to acess Struct property by name as a string in runtime in swiftui
how to acess Struct property by name as a string in runtime in swiftui

Time:05-11

i have an JSON RESPONSE

 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)
        ], 

, now in my code i am using picker and have to dynamically change the key

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

Code where i have to dynamically change

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)

You can see in above code

downloads[index].**abc**

in place of this i need to change def and ghi but dhynamically

In my Home View where i call above file

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

but if i pass it dynamically as a string it gives me error

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

Can you help me how to solve this

CodePudding user response:

A straightforward way is to add a function to your struct that returns the right value for a given key.

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")
    }
}
  • Related