-1

I am trying to build a list that will display multiple @Models. Let's just call them A and B.

Looking at both @Query and FetchDescriptor they only seem to operate on a single type. I want something like @Query<Both_A_and_B>. Is that possible with the current version of SwiftData? Would subclassing(hate this approach already) work, something like that:

@Model
class Entity {}

@Model
class A: Entity {}

@Model
class B: Entity {}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
i-konov
  • 842
  • 1
  • 7
  • 19
  • How about just having two queries? What do you want to do with a `@Query`? Such an idea doesn't make sense to me. – Sweeper Aug 10 '23 at 03:59
  • I want to display a mix of instances of both `A` and `B`. Think of `Apple` and `Orange` and you want to have a query that returns a list of `Fruit` which both `Apple` and `Orange` are. I hope that makes it easier to understand my problem. – i-konov Aug 10 '23 at 04:16
  • I don't know about SwiftData, but since it's just over CoreData, using subclasses works on CoreData. You can fetch for ParentClass, and then check the real class of each entity. – Larme Aug 10 '23 at 08:00
  • 1
    Subclassing doesn't work in SwiftData currently. – Joakim Danielson Aug 10 '23 at 09:38
  • Your possible solutions as I see it is to either merge A and B into one class or to use a separate function that executes two fetches using FetchDescriptor and then combine the resulting arrays into one. – Joakim Danielson Aug 10 '23 at 09:53
  • I tried subclassing an as @JoakimDanielson mentioned it does not work and slaps you pretty early on. I have been thinking about combining A and B into one class with similar properties and internal type do differentiate the specifics like an enum. I am not sure how easy it will be to migrate to separate classes/types if that becomes available in future SD versions but I might be overthinking it. – i-konov Aug 10 '23 at 18:21

0 Answers0