Inderpal Singh
Inderpal Singh

Reputation: 1269

How to filter object from Realm database in Swift

I have realm array and I want to filter objects that contain id = 2 and user_id = 4. Please review my code below.

 for item in realm.objects(data.self).filter("id == 2 && user_id == 4") {
   print(item)
  }

Upvotes: 4

Views: 12413

Answers (3)

Yatin Arora
Yatin Arora

Reputation: 169

Try this:

for item in realm.objects(data.self).filter("id = %@ OR id == %@",2,4) {
  print(item)
}

Upvotes: -1

Inder_iOS
Inder_iOS

Reputation: 1656

You are using the wrong operator in a realm, please check my answer below.

for item in realm.objects(data.self).filter("id == 2 AND user_id == 4") {
   print(item)
}

Upvotes: 8

Ahmad F
Ahmad F

Reputation: 31695

Comparing the id with equality simultaneously with tow values seems to be not logical, id always has ONE value (2 OR 4) but not both, which means that your code should always return an empty array.

If you are aiming to filter the objects based on the value of id if its 2 or 4, you could do it like this:

for item in realm.objects(data.self).filter("id == 2 OR id == 4") {
   print(item)
}

Note that in the predicate you should type "AND" instead of "&&" and "OR" instead of "||". For more details, check: https://realm.io/docs/swift/latest/#filtering

which means that item would be any item that its id is 2 or 4.


Update:

Because of the change of the predicate from:

"id == 2 OR id == 4"

to

"id == 2 && user_id == 4"

What you should simply do -as I mentioned in the above note- is to change "&&" to "AND":

for item in realm.objects(data.self).filter("id == 2 AND user_id == 4") {
   print(item)
}

Upvotes: 3

Related Questions