2

So, basically, the problem is, I have an object, let's call it "Product"

struct Product {
  let categories: [Category]
}

And Category looks like this:

struct Category {
  let id: Int
}

What I need, is to create NSPredicate, that would check if categories list contains Category of certain id. Now sure if it's possible, but maybe there's better workaround than creating another property with simple Int array? Update: NSPredicate is mandatory because I need to use it in Realm database filter query.

2
  • Do you need NSPredicate? There are other, more concise, ways to filter arrays in Swift. Commented Sep 17, 2018 at 8:40
  • So, forgot to mention, I need to use this in a Realm Database, so NSPredicate is mandatory. Commented Sep 17, 2018 at 8:58

3 Answers 3

3

The correct format for your NSPredicate would be:

let predicate = NSPredicate(format: "ANY categories.id == %@", argumentArray: [1])

The above example would return all Products whose categories array contains a Product with the id 1.

Of course, that's assuming that you're only looking for categories of a single id. If you needed to check for multiple ids, you could modify the above with an OR.

Note: I tested the above predicate with an NSArray, not Realm. However, if you check the Realm predicate cheatsheet, it does support all of the operators the predicate is using:

https://academy.realm.io/posts/nspredicate-cheatsheet/?_ga=2.32752254.1161432538.1537175891-1199086799.1527592477

Sign up to request clarification or add additional context in comments.

Comments

0

If you are using Swift you can use filter and contains method to filter arrays.

When you have an array with products you can filter it by:

let filteredProducts = products.filter{ $0.categories.contains(where: { $0.id == 1 })}

The code above filters the products that contains a category with id = 1

Comments

0

You can simply check for the counts of the array returned by filter the categories.

struct Product {
  let categories: [Category]
}

struct Category {
  let id: Int
}

let c1 = Category(id: 1)
let c2 = Category(id: 2)
let c3 = Category(id: 3)

let p = Product(categories: [c1, c2, c3])
let yourCategoryId = 1
let filteredResults = p.categories.filter {
    $0.id == yourCategoryId
}
let isCategoryWithIdPresent = filteredResults.count > 0 ? true : false
print(isCategoryWithIdPresent)

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.