Xcode 16.2 (16C5032a)
FB16300857
Consider the following SwiftData model objects (only the relevant portions are shown) (note that all relationships are optional because eventually this app will use CloudKit):
@Model
final public class Team {
public var animal: Animal?
public var handlers: [Handler]?
...
}
@Model
final public class Animal {
public var callName: String
public var familyName: String
@Relationship(inverse: \Team.animal) public var teams: [Team]?
...
}
@Model
final public class Handler {
public var givenName: String
@Relationship(inverse: \Team.handlers) public var teams: [Team]?
}
Now I want to display Team records in a list view, sorted by animal.familyName, animal.callName, and handlers.first.givenName.
The following code crashes:
struct TeamListView: View {
@Query<Team>(sort: [SortDescriptor(\Team.animal?.familyName),
SortDescriptor(\Team.animal?.callName),
SortDescriptor(\Team.handlers?.first?.givenName)]) var teams : [Team]
var body: some View {
List {
ForEach(teams) { team in
...
}
}
}
}
However, if I remove the sort clause from the @Query and do the sort explicitly, the code appears to work (at least in preliminary testing):
struct TeamListView: View {
@Query<Team> var teams: [Team]
var body: some View {
let sortedTeams = sortResults()
List {
ForEach(sortedTeams) { team in
...
}
}
}
private func sortResults() -> [Team] {
let results: [Team] = teams.sorted { team1, team2 in
let fam1 = team1.animal?.familyName ?? ""
let fam2 = team2.animal?.familyName ?? ""
let comp1 = fam1.localizedCaseInsensitiveCompare(fam2)
if comp1 == .orderedAscending { return true }
if comp1 == .orderedDescending { return false }
... <proceed to callName and (if necessary) handler givenName comparisons> ...
}
}
}
While I obviously have a workaround, this is (in my mind) a serious weakness in the implementation of the Query macro.