尝试使用新的SwiftData框架与谓词,但我收到了一个”不支持的谓词”错误。

huangapple go评论90阅读模式
英文:

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&lt;Memorize&gt; {
            $0.chapter == verse.chapter &amp;&amp;
            $0.verse == verse.verse
        }
        let descriptor = FetchDescriptor&lt;Memorize&gt;(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.

huangapple
  • 本文由 发表于 2023年6月8日 08:26:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定