SwiftData Models and Sort Descriptors Only Work in Release In One Swift File

Hey everyone,

I found a possible SwiftData or Swift compiler bug, that only is visible on Release builds 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, while Debug will just work fine. The errors mentions that keyPathToString cannot be resolved, so I am wondering if in release there is too much optimised or striped away.

I created an example project here. In there we find a file called NeedToStayInOneFile.swift. If you split any of the three declarations there into separate files the above mentioned behaviour is visible.
So this looks like a SwiftData or compiler/codegen issue.

Has anyone faced something similar? Maybe in a different context?

I don’t have any answers here, but I wanted to drop a link to the matching DevForums thread.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple