SwiftData Models and SortDesc. Only Work in One Swift File

Hey everyone,

I found a possible SwiftData Release-only issue with nested sort descriptors on an optional relationship.

In a minimal repro, sorting a @Query by a nested optional relationship key path like:

SortDescriptor(\InvestigationPhotoAsset.imageAnalysis?.overallAestheticsScore, order: .reverse)

works in Debug, but crashes at runtime in Release.

The surprising part is that the crash depends on file layout:

  • if the active SwiftData models and the sort logic are kept in the same Swift file, the app works
  • if the same models are split into separate files, the Release build crashes, 'Debug' will also work

The repro was reduced to just two SwiftData models:

  • InvestigationPhotoAsset
  • InvestigationImageAnalysis

So this looks less like an app-modeling issue and more like a SwiftData/compiler/codegen issue related to nested sort metadata in optimized builds.

If useful, I can also give you a slightly more formal version with a title and code snippet block.

Please check out the code example here

Has anyone faced something similar?

Bug is reported as FB22173905

SwiftData Models and SortDesc. Only Work in One Swift File
 
 
Q