1
votes
let selectedConsoles = ["Xbox", "Playstation 4"]
let players = realm.objects(Person).filter("consoles IN %@", selectedConsoles)

Lets say that player's property consoles is a List<console>()

So I would like to filter all players which has BOTH xbox and playstation 4. Currently I'm able to filter them by OR comparison , my goal is to achieve AND comparison, for example currently it only checks if "xbox" or "playstation 4" exist in player's consoles. I want to return players which has both consoles. Any help or hint will be greatly appreciated

1

1 Answers

2
votes

To get those who have BOTH types of console, you need to "and" them. You need to "or" them together if want those selected that have EITHER. If you "and" them you must have both or it won't be included, if you "or" them, it is included if either exists.

So you need to create a compound "or" predicate. You create a predicate for each case you want to include, and then you "or" [or "and"] together all the predicates using a compound predicate.

I'm making a few guesses based on what you've provided above, but this should be very close. Let me know if it needs clarification or cleaning up. It compiles, but I didn't create a test dataset for it. Substitute your variable name (for your realm object) and class name for the <variable inside angle brackets>.

    let selectedConsoles = ["Xbox", "Playstation 4"]
    let predicateOne = NSPredicate(format:"consoles IN %@", [selectedConsoles[0]])
    let predicateTwo = NSPredicate(format:"consoles IN %@", [selectedConsoles[1]])
    let compoundPredicateEitherConsole = NSCompoundPredicate(orPredicateWithSubpredicates: [predicateOne, predicateTwo])
    let compoundPredicateBothConsoles = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateOne, predicateTwo])
    let results = <realm>.objects(<YourClassName>.self).filter(compoundPredicateEitherConsole)