How to pass @ObservedResults to a SwiftUI sub-View

I have a question about passing an @ObservedResults property to a sub-view. Let’s say I have the following RecordsView where I am first filtering for certain records needing review. I loop through the results and pass individual records to a RecordRowlView. That part I understand.

But separately I also want to use all the filtered records in another sub-view, RecordsSummaryView. My question is, does it make sense to pass in all the filtered records to the subview, and if so, how would that be done (what would the variable type be in the sub-view)? Or would I not pass in anything and then just repeated the @ObservedResults filtered variable in the RecordsSummaryView? Or is there some other way to handle the situation of getting filtered records into a sub-view?

struct RecordsView: View {
    @ObservedResults(Record.self, NSPredicate(format: "needsReview == True")) var reviewRecords
        
    var body: some View {
        VStack {
            ForEach(reviewRecords) { record in
                RecordRowView(record: record)
            }
            RecordsSummaryView(records: reviewRecords)
        }        
    }
}

Thanks!

–Tom

1 Like

Hi @TomF I found a couple of options that work.

The first is for RecordsSummaryView to include @ObservedResults(Record.self, NSPredicate(format: "needsReview == True")) var reviewRecords – where you can then embed that view with RecordsSummaryView().

The second is to keep RecordsView as you currently have it, and then add let results: Results<Record> to RecordsSummaryView (as well as import RealmSwift). I guess you could use this if you don’t need to make any changes to the realm from RecordsSummaryView.

2 Likes

Thanks @Andrew_Morgan. I will use the first method as I do need to make changes in my RecordsSummaryView.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.