SwiftData by Example: iOS 17 & SwiftUI 5 — Part 2
So far we have been able to add book to the database using SwiftData. Let’s continue to build our app and add ability to fetch saved books from saved persistence store.
We will start by building a view to display list of books.
import SwiftUI
struct BookListView: View {
var body: some View {
Text("Hello, DevTechie!")
}
}
#Preview {
BookListView()
}
Start with the import of SwiftData
import SwiftUI
import SwiftData
struct BookListView: View {
We will use newly introduced @Query macro to fetch the list of books. This macro is backed by Query struct which is a property wrapper to fetch set of models and keeps those models in sync with the underlying data.
import SwiftUI
import SwiftData
struct BookListView: View {
@Query private var books: [Book]
We can display these fetched books inside a List view using ForEach view. We are using ForEach view here so we can add delete functionality to our book list.
import SwiftUI
import SwiftData
struct BookListView: View {
@Query private var books: [Book]
var body: some View {
NavigationStack {
List {
ForEach(books) { book in
Text(book.title)…