SwiftData Predicate ridiculous set-contains-check crash in Swift

It is so ridiculous, but I have a crash in this code:

var fetchDescriptor = FetchDescriptor<FactModel>()
fetchDescriptor.fetchLimit = 10
fetchDescriptor.sortBy = [.init(\.showCount, order: .forward)]
let key = category.key
if key != "general" {
    fetchDescriptor.predicate = #Predicate { fact in
        fact.categories.contains(key)
    }
}
        
let result = try modelContext.fetch(fetchDescriptor)

The crash happens on the fetching when the predicate is active. Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

If I change the predicate, all works well. But the problems are only if I use my Set<String> with .contains.

fetchDescriptor.predicate = #Predicate { fact in
    fact.text.contains("a")
}

Please help me understand the issue.

  • Shouldn’t it be fact.categories.contains(category)?

    – 

  • no. categories is Set<String>. Key is String

    – 

  • What does the crash log say?

    – 

  • Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

    – 

  • 1

    The reason is what @Larme linked to that you can’t use a property that is a collection in a predicate. I change from contains to contains(where:) and then got the error message Can't have a non-relationship collection element in a subquery in the console

    – 




Leave a Comment