0

Could I do the following Predicate in Swift 4 to the following string 'name':

let predicate = NSPredicate(format: "name.dropLast() = %@", searchText)

Basically, could I add the extension 'dropLast()' inside the predicate? If not, what is an alternative?

kiwidude89
  • 63
  • 1
  • 7

1 Answers1

0

"Could I do the following"

No. NSPredicate comes with its own completely specified language. Predicate strings must conform to that language; otherwise, they cannot be parsed.

"If not, what is an alternative?"

An alternative to do what? You are not telling us anything about the goal here. For example, instead of calling NSPredicate(format:), you might be able to call NSPredicate(block:) which lets you write the predicate test in Swift code. But you can't do that in all situations. And you have not said what your situation is.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Sorry for not being clear about the alternative. So in my predicate, I would want to drop the last character of 'name'. Only then would I want to match that result with 'searchtext'. Since I cannot use 'dropLast()', how else could I match the first few characters less the last character using NSPredicate? Hope that clarifies. – kiwidude89 Apr 19 '18 at 01:47
  • Yes but in what situation are you using this NSPredicate? What will you hand it to? – matt Apr 19 '18 at 02:05
  • Ah okay. I'm using this to predicate my fetch request from core data. So for example: let request = NSFetchRequest(entityName: "Users") request.predicate = NSPredicate(format: "id.dropLast() = %@", "searchText") – kiwidude89 Apr 19 '18 at 02:14
  • Yes, well, “NSPredicates created with predicateWithBlock: cannot be used for Core Data fetch requests backed by a SQLite store.” so you’re stuck using the format language. You might be able to make some headway by using a MATCHES expression, but you can’t magically introduce Swift into the mix. – matt Apr 19 '18 at 03:15
  • Oh bummer. Alrighty, thank you so much for the advice and tips. Will see what MATCHES can do :) – kiwidude89 Apr 19 '18 at 03:49
  • Alternative just fetch more objects than you really need and filter the result. – matt Apr 19 '18 at 04:16