0
votes

I have a problem with NSPredicate format in Swift, I want to create a predicate that compares an Int value, functioning like "contains" or "LIKE" in String value.

Example :

  • 1
  • 12
  • 31
  • 511

If I type 1, then all numbers will be returned to predicate.

This is my line code looks like :

let searchPredicate = NSPredicate(format: "id LIKE %d OR customerName contains %@", searchText, searchText)

I also had tried :

let searchPredicate = NSPredicate(format: "id contains %d OR customerName contains %@", searchText, searchText)

But both above gave me error : 'Operator 'LIKE' not supported for type int' and 'Operator 'contains' not supported for type int'

Any ideas are greatly appreciated! Thank you in advance.

2
You would need to convert your customer numbers to strings - Paulw11
@Paulw11: Do you mean convert "id" to String inside NSPredicate? - Aditya Purwa
No, you would need to store your id as a string in your database. You can only use LIKE on strings - Paulw11
Is this for Core Data, or why do you need a NSPredicate? Can't you store the numbers as strings? - Martin R

2 Answers

0
votes

For int values you can directly use "==" operator and no need of LIKE operator, you can use the following predicate format,

let searchPredicate = NSPredicate(format: "id == %d OR customerName contains %@", searchText, searchText)

And if your using NSNumber then make sure that you get the actual value using the predefined methods, like intValue,

-1
votes

Can you please try this

let searchPredicate = NSPredicate(format: "id LIKE %d OR customerName contains %@", String(format: "%@",searchText), String(format: "%@",searchText))