Auto Save Records in SwiftData & SwiftUI

DevTechie
DevTechie
Published in
6 min readMay 8, 2024

--

Auto Save Records in SwiftData & SwiftUI

SwiftData simplifies data persistence by handling tasks in the background for us. One of its features is the convenience of automatically saving a record when it’s added or changed in the model context.

The auto saving feature is on by default, meaning changes in the model context are automatically saved. But what if we want more control? In some cases, our apps may need the option to commit changes manually, giving users the chance to undo or redo before saving the data into the data store.

Let’s explore how the auto saving works and how disabling it gives us greater control over the persisted data.

We will look at the pantry management example to understand the concept better.

PantryItem model:

import Foundation
import SwiftData
import SwiftUI

@Model
class PantryItem {
var name: String
var quantity: String
var expirationDate: Date?

init(name: String, quantity: String, expirationDate: Date? = nil) {
self.name = name
self.quantity = quantity
self.expirationDate = expirationDate
}
}
extension PantryItem {
var displayExpDate: String {
guard let expDate = expirationDate else {
return ""
}
if expDate <= Date() {
return "Expired on " + expDate.formatted(date: .numeric, time…

--

--