Core Data - FetchRequest Woes: instance member used in param won't run before initializer

I want to create a star-based rating display using feedback from users who visit a particular real world landmark. In Core Data I have an entity called Rating with attributes called rating (Int32) and landmark (String). I want to get the average for all rating(s) associated with a given landmark in order to display stars in the view for each. Here is the code for the View:

struct TitleImageView: View {
            @Environment(\.managedObjectContext) var viewContext : NSManagedObjectContext
            let landmark: Landmark 
            var body: some View {
                
                Image(landmark.imageName)
                    .resizable()
                    .shadow(radius: 10 )
                    .border(Color.white)
                    .scaledToFit()
                    .padding([.leading, .trailing], 40)
                    .layoutPriority(1)
                    .overlay(TextOverlay(landmark: landmark))
                    .overlay(RatingsOverlay(rating: stars))
            }
        }

Here’s the fetch request:

let fetchRequest = Rating.fetchRequestForLandmark(landmark: landmark.name)
    var ratings: FetchedResults<Rating> {
            fetchRequest.wrappedValue
    }
        var sum: Int32 {
            ratings.map { $0.rating }.reduce(0, +)
        }
        var stars : Int32 {
            if (ratings.count > 0) {
                return sum / Int32(ratings.count)
            } else {
                return 0
            }
        }

This gives me the warning:

Cannot use instance member ‘landmark’ within property initializer; property initializers run before ‘self’ is available

I tried wrapping the fetch in a calculated property. The warning went away, and the build succeeded; however, in this case, the fetch always turns up empty (ratings.count is always 0), even when I know there is data there. (I’ve checked and double-checked.)
I’m returning to this problem after having given up for a while.
I am in no way married to this approach. Surely, there is a way to do what I want to do. If anyone can guide me in the right direction, I will be very grateful. Thanks

This topic was automatically closed after 166 days. New replies are no longer allowed.