@Observable conflict with @Query

If I annotate a class with @Observable I get this error in @Query:

Expansion of macro 'Query()' produced an unexpected 'init' accessor

If I remove @Observable the error goes away.

Elsewhere I have .environment referencing the class. With @Observable this complains that the class needs to be @Observable.

I am mystified. Does anyone have a suggestion?

Replies

Here are two versions of the expanded macro - the first with @Observable, the second without. As far as I can see the expansions are identical. However the expansion of @Observable adds @ObservationTracked before the query, so that must be the cause of the error. I can find no explanation anywhere in the documentation or searching online. I'm thinking it's a bug.

Using the @Query macro under the @Observable macro may not be a very correct use. In this case, I recommend you to change the structure of your code if you can. If you give more information about what you want to do, I will be happy to help :)

Thanks. You are probably correct, but I can't find any docs to support this. Anyway, I have started using the Query struct. See my later post about this. https://developer.apple.com/forums/thread/751155

If you are going to make only a simple query, I recommend you to do it in MainView. However, if you are going to apply operations to your data, it may make sense to query in the View Model. According to the research I did, before querying, you need to pass the modelContext to the View Model and then use FetchDescriptor. If you search Query in View Model on the internet, you can get more detailed information. If you have any questions, please feel free to ask. I will be happy to help you.