SwiftData SortDescriptor Limitation...

  • I built a SwiftData App that relies on CloudKit to synchronize data across devices.
  • That means all model relationships must be expressed as Optional.
  • That’s fine, but there is a limitation in using Optional’s in SwiftData SortDescriptors (Crashes App)
  • That means I can’t apply a SortDescriptor to ModelA using some property value in ModelB (even if ModelB must exist)
  • I tried using a computed property in ModelA that referred to the property in ModelB, BUT THIS DOESN”T WORK EITHER!

Am I stuck storing redundant data In ModelA just to sort ModelA as I would like???

Not entirely sure what your issue is here. You say something crashes, but you don't explain what the crash is, so it's not possible to see whether you're doing something wrong or if there is a genuine issue in Apple's code.

You haven't provided any code whatsoever, so I really can't give you any help at all.

Can you provide some code that explains your issue properly?

I am not asking for help fixing a crash. I did that by commenting out one line of code where I was asking SwiftData to sort ModelA results on a title string from an associated ModelB object. ModeB has a one to many association to ModelA and must exist before any ModelA objects are created BUT CloudKit requires that you specify the relationships between these two models as Optional. Therefore when I tried to sort ModelA results by a Title in ModelB I needed to declare the property as a force unwrapped title of ModelB in the SortDescriptor. It would be ludicrous to try to show the actual code so that you can follow everything.

Suffice it to say that this SortDescriptor was accepted by the compiler, and gave me exactly what I wanted when I ran the App either in a Simulator or on a device that downloaded the app from Xcode. BUT when the app was uploaded to the App Store and then downloaded from TestFlight the App would immediately crash with no useful error pointing to the problem.

Bottom line is I found the issue after months of digging and now I just want to restore the capability I had before I had to comment out that line of code. As I said I tried using a computed property in ModelA (rather than store the title from ModelB it would fetch it when needed) and used that computed property as the sort descriptor but although this is also accepted by the compiler this fails as well.

I suppose I can do a sort on the array AFTER it is fetched by SwiftData but that seems less efficient. Anyway wondering if anyone else has run into this limitation and has found a better workaround.

SwiftData SortDescriptor Limitation...
 
 
Q