swiftpredicateswiftdata

Does the #Predicate macro in Foundation/SwiftData support case-insensitive search?


I'm testing the new SwifData framework and working with the new #Predicate macro and realized that it doesn't support case-insensitive search. The macro does not work with the lowercased() method or the localizedLowercase property, so there seems to be no way to create a case-insensitive predicate, as we used to do with NSPredicate and the [c] attribute.

   var predicate = #Predicate<Book> {
  $0.title.localized().contains(search) }

Error: The lowercased() function is not supported in this predicate (from macro 'Predicate')

I wonder if there is any work around. Thanks


Solution

  • The new Predicate macro works pretty well with the localizedStandardContains(_:) function.

    From the Apple dev documentation website:

    This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.

    Usage:

    let userInput = "foo bar"
    let predicate = #Predicate<Book> { $0.title.localizedStandardContains(userInput) }