Skip to content

Sorting Items in SwiftData using @Query

iOS, Swift, SwiftData, Database1 min read

SwiftData is a powerful new tool for managing data in Swift applications. One of its key features is the @Query property wrapper, which allows you to fetch and sort data from your database. In this blog post, we'll explore how to use the order parameter of @Query to sort items in your database.

Understanding @Query

@Query is a property wrapper provided by SwiftData that allows you to fetch data from your database. It takes a sort descriptor and an order parameter to determine how the fetched data should be sorted.

Here's a quick example of how you might use @Query in a SwiftUI view:

1import SwiftUI
2import SwiftData
4// The view for home
5struct HomeView: View {n
6 @Environment(\.modelContext) private var context
7 @Query private var notes: [Note]
9 private func createNote() {
10 // TODO: Add logic to create a note with context
11 }
13 var body: some View {
14 VStack {
15 List {
16 ForEach(notes) { note in
17 Text(note.text)
18 }
19 }
20 }
21 .navigationBarTitleDisplayMode(.inline)
22 .navigationTitle("Notes")
23 }
26// The model
28final class Note {
29 var text: String
30 var created: Date
32 init(
33 text: String = "",
34 created: Date = Date()
35 ) {
36 self.text = text
37 self.created = created
38 }

As you can see, above we are using @Query above to fetch a list of notes.

About Sorting

If you wanted to sort the Notes by a specific key - created(a Date) for example - you could do it like this:

1@Query(sort: \Note.created, order: .reverse) private var notes: [Note]

In this example, @Query is fetching Note objects from the database and sorting them based on the created property. The order parameter is set to .reverse, which means the notes will be sorted in descending order, with the most recently created notes appearing first.

Sorting in Ascending Order

If you want to sort your items in ascending order, you can use the .forward value for the order parameter. Here's how you would modify the above example to sort the notes in ascending order:

1@Query(sort: \Note.created, order: .forward) private var notes: [Note]

Now, the notes will be sorted in ascending order, with the oldest notes appearing first. If you actually look at the code for @Query .forward is the default value so you can just leave it out as well:

1@Query(sort: \Note.created) private var notes: [Note]