Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm: Filter with IN Operator

Tags:

swift

realm

I have an array of Integers:

▿ 2 elements
  - [0] : 123459
  - [1] : 1031020

And would like to filter my objects based on the array.

.filter("code IN \(myCodeArray)")

But this results in a crash. How do I use the IN operator correctly?

like image 942
netshark1000 Avatar asked Mar 06 '16 09:03

netshark1000


1 Answers

Instead of using Swift's string interpolation, you should use NSPredicate's argument substitution support via %@:

.filter("code IN %@", myCodeArray)

Swift's string interpolation syntax ("\(someVariable)") inserts a string representation of the variable into the string. The string representation of your array of integers is [123459, 1031020], which is not valid in an NSPredicate format string. Using %@ substitutes the object into the predicate without needing to worry about whether the Swift string representation of the object matches what NSPredicate expects.

like image 124
bdash Avatar answered Nov 07 '22 13:11

bdash