How to use the modern declarative SwiftData framework for persistent data storage in new iOS projects?
The SwiftData framework is a modern replacement for Core Data, built specifically for the Swift ecosystem. It uses macros to simplify data model definitions and integrates seamlessly with SwiftUI through reactive UI update mechanisms.
To get started, you need to declare a data model class using the special Model macro. Properties inside this class automatically become persistent fields, eliminating the need to manually configure complex entity and attribute schemas.
At the application or root view level, you configure the data container using the modelContainer modifier. This allows you to inject the persistence context into the SwiftUI environment and make data available for reading and writing in all child components.
To fetch saved objects in the UI, the special Query macro is used. It automatically updates the view upon any changes in the database, whether it is adding a new record, deleting, or editing existing items.
Data modification occurs through the standard model context, which can be retrieved from the environment. You simply create a new instance of your model, insert it into the context, and the framework automatically takes care of saving changes when the app closes or loses focus.