英文:
Trying to use the new SwiftData framework with a predicate, but I am receiving an "Unsupported Predicate" error
问题
以下是您要翻译的内容:
我正在尝试在我的SwiftUI项目中运行一个使用SwiftData的函数。
相关的函数如下:
private func forgetVerse() {
withAnimation {
let predicate = #Predicate<Memorize> {
$0.chapter == verse.chapter &&
$0.verse == verse.verse
}
let descriptor = FetchDescriptor<Memorize>(predicate: predicate)
do {
let objects = try context.fetch(descriptor)
context.delete(objects.first!)
} catch {
print(error)
}
}
}
当我运行这个函数时,我收到以下错误:
SwiftDataError(_error: SwiftData.SwiftDataError._Error.unsupportedPredicate)
我对这个错误不太熟悉,也找不到任何相关信息。我使用#Predicate
的方式有什么问题吗?
供参考,这是我的模型:
@Model
final class Memorize {
var chapter: Int
var verse: Int
init(chapter: Int, verse: Int) {
self.chapter = chapter
self.verse = verse
}
}
英文:
I am trying to run a function in my SwiftUI project utilizing SwiftData.
The function in question:
private func forgetVerse() {
withAnimation {
let predicate = #Predicate<Memorize> {
$0.chapter == verse.chapter &&
$0.verse == verse.verse
}
let descriptor = FetchDescriptor<Memorize>(predicate: predicate)
do {
let objects = try context.fetch(descriptor)
context.delete(objects.first!)
} catch {
print(error)
}
}
}
When I run this function, I get the following error:
>SwiftDataError(_error: SwiftData.SwiftDataError._Error.unsupportedPredicate)
I am not familiar with this error, and I am not able to find any information on it. Is there something wrong with my approach to using #Predicate
?
For reference, here is my model:
@Model
final class Memorize {
var chapter: Int
var verse: Int
init(chapter: Int, verse: Int) {
self.chapter = chapter
self.verse = verse
}
}
答案1
得分: 2
"A predicate can’t contain any nested declarations, use any flow control such as for loops, or modify variables from its enclosing scope. However, it can refer to constants that are in scope."
I suppose your variable verse
is not a constant.
英文:
https://developer.apple.com/documentation/foundation/predicate
"A predicate can’t contain any nested declarations, use any flow control such as for loops, or modify variables from its enclosing scope. However, it can refer to constants that are in scope."
I suppose your variable verse
is not a constant.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论