尝试在视图中初始化 SwiftData 查询时收到以下错误:
Error: Cannot convert value of type 'PredicateExpressions.Equal<PredicateExpressions.KeyPath
<PredicateExpressions.Variable<Array<Todo>.Element>, Int>, PredicateExpressions.KeyPath<PredicateExpressions.Value<Section>,
Int>>'(aka'PredicateExpressions.Equal<PredicateExpressions.
KeyPath<PredicateExpressions.Variable<Todo>, Int>, PredicateExpressions.KeyPath<PredicateExpressions.Value<Section>,
Int>>') to closure result type 'any StandardPredicateExpression<Bool>'
TodoView.swift
import SwiftUI
import SwiftData
struct TodoView: View {
@Query var todos: [Todo]
@EnvironmentObject var currentSection: Section
@Environment(\.modelContext) var modelContext
var DWMY = ["D","W","M","Y"]
var body: some View {
List {
ForEach(todos) { todo in
HStack {
if todo.completed == false {
Text("[ ]")
} else {
Text("[X]")
}
Text(todo.name)
Text(DWMY[todo.section])
}
}
.onDelete(perform: deleteToDo)
}
.navigationBarTitleDisplayMode(.inline)
}
init(todoSection: Section) {
_todos = Query(filter: #Predicate { todo in
todo.section == currentSection.section
})
}
func deleteToDo(at offsets: IndexSet ) {
for offset in offsets {
let todo = todos[offset]
modelContext.delete(todo)
}
}
}
当我尝试为查询提供值时会发生错误,currentSection.section
如果我currentSection.section
用硬编码的Int替换则不会出现任何错误。
据我所知,发生这种情况是因为我的环境ToDoView.swift
直到Body创建后才被传递下去,因此发生currentSection.section
时不存在init
。
currentSection.section
将我的价值传递到的正确方法是什么init
?
我将使
TodoView
不依赖于环境对象来创建Query
。 将init
纳入部分编号。EnvironmentObject
然后在父视图中获取: