SwiftUI Combining two ObservedObjects from two different arrays

Viewed 133

i try to combine two objects from the following types

@ObservedObject var expenses = Expense()
@ObservedObject var recipes = Recipe()

The arrays worked quite good and everything is fine.

Now i would like to present all items from the arrays in a ForEach.

    var body: some View {
    TabView {
        NavigationView {
            List {
                ForEach(Array(zip(expenses.items, recipes.ReItems)),id: \.0){ item in
                    HStack{
                        VStack(alignment: .leading){
                            Text(item.beschreibung)
                                .font(.headline)
                            Text(String(item.menge) + " \(item.unitType)")
                        }
                    }
                }
                .onDelete(perform: removeItems)
            }

But this throws an error - "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions"

My first idea was to save the arrays in a variable like in this stackoverflow post The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

@State private var arrayExpense = self.expenses.items
@State private var arrayRecipes = self.recipes.ReItems

But to be hoonest, this looks not good.. It also throws an exception ;o

Thanks for your help!

2 Answers

Try to break it apart, like below (this gives compilers explicitly type check result of zip)

var body: some View {
    TabView {
        NavigationView {
            List {
              self.listContent(items: Array(zip(expenses.items, recipes.ReItems)))
            }
    ...


private func listContent(items: [Item]) -> some View {
    ForEach(items, id: \.0){ item in
        HStack{
            VStack(alignment: .leading){
                Text(item.beschreibung)
                    .font(.headline)
                Text(String(item.menge) + " \(item.unitType)")
            }
        }
    }
    .onDelete(perform: removeItems)
}

should the Text be:

Text(item.0.beschreibung).font(.headline)
Text(String(item.0.menge) + " \(item.0.unitType)")

or with item.1 as the case maybe.

Related