Chapter 19
Working with Database and SwiftData
Learn not to add too many features right away, and get the core idea built and tested.
– Leah Culver
Congratulations on making it this far! By now you've already built a simple app for users to list their favorite restaurants. If you've worked on the previous exercise, you should understand the fundamentals of how to add a restaurant; I've tried to keep things simple and focus on the basics of UITableView. Up to this point, all restaurants have been predefined in the source code and stored in an array. If you want to add a restaurant, the simplest way is to append the new restaurant to the existing restaurants
array.
However, if you do it that way, you can't save the new restaurant permanently. Data stored in memory (e.g. array) is volatile. Once you quit the app, all the changes are gone. We need to find a way to save the data in a persistent manner.
To save the data permanently, we'll need to save in a persistent storage-like file or database. By saving the data to a database, for example, the data will be safe even if the app quits or crashes. Files are another way to save data, but they are more suitable for storing small amounts of data that do not require frequent changes. For instance, files are commonly used for storing application settings like the Info.plist file.
The FoodPin app may require storage for thousands of restaurant records, with users frequently adding or removing records. In such cases, a database is an appropriate solution for managing a large dataset. In this chapter, I will guide you through the SwiftData framework and demonstrate how to utilize it to handle database operations. We will cover topics such as creating the data model and performing CRUD (create, read, update, delete) operations using the SwiftData framework.
To access the full version of the book, please get the full copy here. You will also be able to access the full source code of the project.