我尝试组合以下类型的两个对象
@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
感谢您的帮助!
最佳答案
尝试将其分解,如下所示(这使编译器显式类型检查 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)
}
关于arrays - SwiftUI 组合来自两个不同数组的两个 ObservedObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61169658/