Looping multiple arrays with ForEach SwiftUI

Viewed 777

UI: https://imgur.com/a/0BbJBFc

I'm using the ForEach to iterate over an array of minerals in the example code, but I can't find a proper solution to loop the second array (mineral amount) right underneath the minerals.

In different project, I made it so far that the ForEach loops both arrays but for every mineral displays all amount for the Planet and for the second mineral all amount for the Planet and so on.

I did create a new struct with both arrays but without success. Adding a binding property also failed. I hope to learn a new swift method to achieve the desire look.

Data File

import Foundation

struct Planet: Identifiable {
    var id = UUID()
    var name: String
    var minerals: [String]
    var mineralAmount: [String]
}

let planetsData: [Planet] = [

Planet(name: "Jupiter", minerals: ["Iron", "Gold", "Copper"], mineralAmount: ["10K", "20K", "30K"]),
Planet(name: "Earth", minerals: ["Lithium", "Aluminium", "Quartz"], mineralAmount: ["40K", "50K", "60K"])
]

ContentView

import SwiftUI

struct ContentView: View {
    
    var planet: Planet
    var body: some View {
    
      VStack() {
        ForEach(planet.minerals, id: \.self) { item in
            Text(item)
                .font(.system(size: 22, weight: .regular))
                        .foregroundColor(.primary)

                        Text("amount to be added")
                            .font(.system(size: 22, weight: .regular))
                            .foregroundColor(.primary)

                    }
                }
            }
        }
    

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
            ContentView(planet: planetsData[0])
        }
    }


  [1]: https://i.stack.imgur.com/4MDKs.png
2 Answers

You can achieve it this way:

ScrollView {
    VStack (alignment: .leading) {
        ForEach(0..<planet.minerals.count) { i in
            HStack {
                Circle()
                    .frame(width: 50, height: 50)
                    .foregroundColor(.black)
                    
                VStack (alignment: .leading) {
                    Text(planet.minerals[i])
                        .font(.system(size: 22, weight: .regular))
                        .foregroundColor(.primary)
                    Text(planet.mineralAmount[i])
                        .font(.system(size: 22, weight: .regular))
                        .foregroundColor(.secondary)
                }
            }
            
        }
        Spacer()
    }
}

why don't you create a dictionary from both values

mineralsDic = [minerals: mineralAmount] 

I of course know the syntax of dictionary but I just try to explain my idea + instead of making 2 loops you can make only one which has less complexity and better performance

Related