— iOS, Swift, SwiftData, Database — 1 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.
@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 SwiftUI2import SwiftData3
4// The view for home5struct HomeView: View {n6 @Environment(\.modelContext) private var context7 @Query private var notes: [Note]8 9 private func createNote() {10 // TODO: Add logic to create a note with context11 }12 13 var body: some View {14 VStack {15 List {16 ForEach(notes) { note in17 Text(note.text)18 }19 }20 }21 .navigationBarTitleDisplayMode(.inline)22 .navigationTitle("Notes")23 }24}25
26// The model27@Model28final class Note {29 var text: String30 var created: Date31 32 init(33 text: String = "",34 created: Date = Date()35 ) {36 self.text = text37 self.created = created38 }39}
As you can see, above we are using @Query above to fetch a list of notes.
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.
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]