SwiftData is Apple's modern framework designed to simplify data management in Swift applications.
SwiftData aims to reduce the boilerplate code and complexities involved in data persistence, making it easier for developers to manage data across different layers of their applications. It's deeply integrated into Swift, taking advantage of modern Swift language features like property wrappers and protocols.
Getting Started with SwiftData
Let's start defining what models are we going to save persistently. To do this we just need to tag our model with the attribute @Model
. This attribute requires that we declare our model as a class
.
@Model
class Task {
var title: String
var isCompleted: Bool
init(title: String, isCompleted: Bool = false) {
self.title = title
self.isCompleted = isCompleted
}
}
All the instances of our model will be saved in a ModelContext
. In order to access to it, we will declare it as an @Environment
variable.
@Environment(\.modelContext) var modelContext
This means that we need to inject it when we create the view. The simplest way is using the modelContainer(for)
modifier.
ContentView()
.modelContainer(for: TodoTask.self)
Once everything is set up, let's create a to-do task app as we normally would, but with two small differences:
- We replace
@State
with@Query
on our tasks array declaration. This will retrieve the data from the ModelContext. - When we add, edit, or delete a task, we'll make the changes in our
modelContext
instead of ontasks
array.
@Query var tasks: [TodoTask] = []
@State var text: String = ""
var body: some View {
List(tasks) { task in
HStack {
Image(systemName: task.isCompleted ? "checkmark.square" : "square")
.resizable()
.frame(width: 24, height: 24)
Text(task.title)
}
.onTapGesture {
task.isCompleted.toggle()
}
}
HStack {
TextField("Add a task...", text: $text)
.textFieldStyle(.roundedBorder)
Button(action: {
guard !text.isEmpty else {
return
}
modelContext.insert(TodoTask(title: text))
text = ""
}, label: {
Text("Add")
})
}
.padding()
}
Result
When you run the App you'll observe that every change done in the list will be stored persistently so when the App is killed and launched again, the data will be still there.
You can find all this code together in our samples repository, here.
Be the first to comment