TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SwiftData Filter by object and relationship?

Forums > SwiftUI

I have two Model classes: List and ListItem that are related where List is the parent. The ListItem model has 2 objects: name and type.

I have a screen that I want to display items from a specific list grouped by type. Since (as far as my research has shown) SwiftData can't do a simple GROUP BY, I need 6 different variables (one for each type) and then 6 different ForEach statements with the same UI code inside, one for each variable (why? why? but ok).

Where I'm stuck is writing a predicate based on a parent field. I'm passing in the list from the prior View so I tried this:


 @State var list: List

    @Query(filter: #Predicate<ListItem> { item in
        item.list == list && item.type == "Clothing"
    }) var clothing: [ListItem]

The error I get says that list cannot be used on type 'ListView'. Is there a way to filter by the parent related item and an object in the model at the same time?

   

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.