Search code examples
swiftuixcode11

How to loop through keys in struct for SwiftUI?


I have done XCode a long time ago and now coming back to pick up SwiftUI. I am trying to render the data of a struct in a HStack.

The struct looks like this:

struct Product: Hashable, Codable{
    var column0: Int
    var column1: String
    var column2: String
    var column3: String
    var column4: String
}

Inside the view body there's something like this:

var pdt: Product
var body: some View {
        HStack {
             Text(pdt.column1)
             Text(pdt.column2)
        }
}

The above will work, but I didn't want to hardcode column1 or column2 because the number of columns will differ. How can I use pdt as a Dictionary and loop through the keys so that I can display all columns?

Many thanks in advance!


Solution

  • Here is a demo of possible approach (for this simple case) - you can reflect properties and map them to shown values (for custom/complex types it will require more efforts by idea should be clear).

    var body: some View {
        let columnValues = Mirror(reflecting: pdt)
                              .children.map { "\($0.value)" }
        return HStack {
            ForEach(columnValues, id: \.self) { Text($0) }
        }
    }