swiftormswiftdata

How to filter a list of String when using SwiftData


I have a model like this:

@Model
final class MyModel: Identifiable, Equatable,ObservableObject {
    @Attribute(.unique) public let id: UUID
    ...
    var searchables: [String] = []
descriptor.predicate = #Predicate<MyModel> { item in
   item.searchables.contains(where: { $0.localizedStandardContains(searchQuery) })
}

However, it gives me the following error:

Can't have a non-relationship collection element in a subquerySUBQUERY...

What is the correct way to perform this kind of query? Is it even supported in SwiftData?


Solution

  • This article may be relevant https://www.hackingwithswift.com/quick-start/swiftdata/using-structs-and-enums-in-swiftdata-models

    However, there is a catch: if you use collections of value types, e.g. [String], SwiftData will save that directly inside a single property too. Right now it’s encoded as binary property list data, which means you can’t use the contents of your array in a predicate.