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

Thanks for filing the feedback report. Is this issue the same as the one discussed here?

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Two bits of administrivia:

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I saw this post, but have not found anything there about the "one file works, separate files crashes" aspect. So I submitted a post. But in general yes, it is also about sorting on optional nested relationships.

@nilsn26: Thanks for your feedback report and confirmation. I don't have a clear answer about why putting the models and the sort logic in a same Swift file avoids the crash either, but I think the technical nature here is that KeyPath.appending can't forward optionality, which is a known issue under the investigation of the Swift team.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Interesting. Is there any issue where I could track that status on the swift language? And is there any other known workaround beside copying the related declarations together in one file?

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