【问题标题】:SwiftUI Combining two ObservedObjects from two different arraysSwiftUI 组合来自两个不同数组的两个 ObservedObjects
【发布时间】:2020-04-12 09:59:54
【问题描述】:

我尝试组合以下类型的两个对象

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

阵列工作得很好,一切都很好。

现在我想在 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)
            }

但这会引发错误 - “编译器无法在合理的时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式”

我的第一个想法是将数组保存在一个变量中,就像这个 stackoverflow 帖子一样 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

但老实说,这看起来不太好.. 它也会抛出异常;o

感谢您的帮助!

【问题讨论】:

    标签: arrays swift swiftui


    【解决方案1】:

    尝试将其分解,如下所示(这使编译器显式地对 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)
    }
    

    【讨论】:

    • @Ashtari,真的Item 只是我对演示的假设,因为您没有提供您的物品的真实类型。显然,您的 .items 应该有类型。要获得能够复制粘贴的答案,您必须提供有问题的复制粘贴可测试代码。 ;)
    • sry 在漫长的夜晚有点累了.. :x 是的,它现在可以工作了。谢谢你:)
    【解决方案2】:

    文本应该是:

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

    或以 item.1 为例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      相关资源
      最近更新 更多