You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用swiftdata-sectionedquery时ForEach泛型参数V无法推断问题

解决swiftdata-sectionedquery遍历元素时的"Generic parameter 'V' could not be inferred"错误

问题原因

你遇到的错误是因为遍历SectionedResults时,外层ForEach(items)返回的每个对象是分区Section实例(包含分区标识和该分区下的元素集合),而非直接的元素数组。直接对Section实例使用ForEach,SwiftUI无法推断出要遍历的集合类型,因此抛出参数推断失败的错误。

另外你的模型类存在一个潜在问题:SwiftData的模型必须通过@Model宏标记才能被框架管理,你的FoodItem类缺少这个标记,可能会导致后续其他问题。

修复步骤

1. 修正模型类

给FoodItem添加@Model宏,同时保留Hashable以满足swiftdata-sectionedquery包的要求:

@Model
class FoodItem: Hashable {
  var calories: Int
  var dateString: String
  var image: String
  var mealType: String
  var name: String
  var timestamp: Int64
  @Relationship(deleteRule: .cascade) var foodItems: [ItemsInMeal] = []
  @Relationship(deleteRule: .cascade) var nutrition: Nutrition?

  init(...) { ... }
}

2. 修正视图中的遍历逻辑

明确访问Section实例的elements属性(该属性存储了当前分区下的所有FoodItem元素):

struct FilteredMeals: View {
  @Environment(\.modelContext) var modelContext
  @SectionedQuery var items: SectionedResults<String, FoodItem>
 
  var filter: String

  @State private var newSelection: Set<String> = []

  init(filter: String) {
    self.filter = filter
    _items = SectionedQuery(
      \.dateString,
      filter: #Predicate<FoodItem> { item in 
        item.name.starts(with: filter)
      }
    )
  }

  var body: some View {
    NavigationStack {
      List {
        // 外层遍历分区,变量名改为section更清晰
        ForEach(items) { section in
          Section {
            if newSelection.contains("\(section.id)") {
              // 遍历分区下的elements集合
              ForEach(section.elements) { food in 
                // 你的元素视图内容
              }
            }
          } header: { 
            // 分区头内容
          }
        }
      }
    }
  }
}

补充说明

SectionedResults<SectionKey, Element>的每个元素是一个内置的Section结构体,包含两个核心属性:

  • id: 你指定的分区键(这里是dateString)
  • elements: 当前分区下的所有数据元素集合(这里是[FoodItem])

必须通过elements属性才能访问到分区内的具体数据,直接遍历Section实例会导致类型推断失败。

内容的提问来源于stack exchange,提问作者Neglected Sanity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 14:14:52