考虑 SwiftData 中的以下关系:
@Model
class Category: Decodable, Identifiable {
var id: Int
var title: String
@Relationship var questions = [Question]()
}
@Model
class Question: Decodable, Identifiable {
var id: Int
@Relationship var category: Category?
}
当我在保存问题后尝试从类别中获取所有问题时,就会出现问题:
let catId = 7
let categoryPredicate = #Predicate<Category> { $0.id == catId }
let categoryDescriptor = FetchDescriptor(predicate: categoryPredicate)
let categories = try modelContext.fetch(categoryDescriptor)
if let cat = categories.first {
cat.questions = parsedQuestions
}
//now try to fetch the questions out of the modelContext so they can be used and updated
let questionPredicate = #Predicate<Question> { $0.category.id == catId } //THIS LINE THROWS THE ERRORS
let questionDescriptor = FetchDescriptor(predicate: questionPredicate)
do {
questions = try modelContext.fetch(questionDescriptor)
} catch {
fatalError("unable to find any questions for \(category.title)")
}
我收到这组错误:
无法推断通用参数“ID”
在“可选”上引用实例方法“id”要求“类别”符合“视图”
类型“(ID)->某些视图”不能符合“BinaryInteger”
在这种情况下,如何编写正确的谓词而不出现错误?
由于您的关系是可选的,因此您需要在谓词中使用可选