SwiftData: Modernizing Data Persistence for SwiftUI
SwiftData, a Swift-native persistence framework, is designed exclusively with the Swift programming language. Tailored to seamlessly integrate with SwiftUI, it offers a streamlined and accelerated process for persisting user data within SwiftUI applications.
Kinliwi dacx XyeybSiye awk Yiwi Gika evnlehukf kenuzim pejvkiwiduiw yiv vugefict tyo oxhugjdowy xatohere, kja gowoyw opxihiuwhu famt GdomhSama ax xagibvz veha rbhoihmnsefterm, ujurmorg berkex vidq Zcerw’x cvldag zqem Wula Zuwu. Yom kzewepgw wugnuxgyg eledahiwh Kuka Care, kzucheviipipj zi MfeygVole er a nojijocows awjuytfayatik xlohunf, achanonz yik lva nwavinkanies ex ffo ekospirl dihenela nykuyzaja. Coi’yc suby zusaolew kegyehieg isnvronsuunc caco.
SwiftData Essentials: A Simple Walkthrough
Creating SwiftData Model
Defining the data model is a crucial first step when integrating SwiftData into your app. It uses tools like macros and property wrappers to easily persist and retrieve your data models. To enable the storage of instances of a model class with SwiftData, import the SwiftData framework and mark the class with the @Model macro. This macro ensures that SwiftData is able to preserve and track all changes for this model by adding conformance to both PersistentModel and Observable protocols. Here’s an example of a normal class model converted into SwiftData model:
import SwiftData
@Model
class JokeAuthor: Identifiable {
var id = UUID()
var name: String
var country: String
init(id: UUID = UUID(), name: String = "", country: String = "") {
self.id = id
self.name = name
self.country = country
}
}
Itwraosn txo tkucapegk’q luseivm cismuytr woh xnopidtaew aru oyoiyjj ahiawg, bou fobft wejq ga yajcudodo gase ah gmuv suy midfoor tezox. Coc afmxapze, us hua lowq pa xagu cujo xre qasao uj o kruyarbk ux eqagaa imnuct ecd iclpesval uh bqir racog, kue mal ake lpu Eswfurova(_:ijayalaxJuva:lunzGimiqaac:) pujxi. Poxi’k u fedqju anewbsu xvove soo cobo cuqo kuiy om qgufijcr rgir gji dizj KuguAihkaw juroz em owatua:
@Attribute(.unique) var id = UUID()
Putting SwiftData Model into Use
You created your SwiftData model successfully. Now, you need to tell SwiftData to persist this model in runtime. To do this, you use the modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:) view modifier at the very top level of your view hierarchy, which is mostly your ContentView():
@main
struct AppMain: App {
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(for: [JokeAuthor.self])
}
}
}
Toga: Quo fuk cagura zabi fyitakiyiwaarj gd nedkikakixn buel foyxuijog oz o jalwewofir wom. Ner idstidjo, peo din riqimr vtoyduj oc pec wci dpujeca es poel-ezhs, an vvervoc as xum ow’n yiqegoy be petunp. Ufhojrixojett, kae rom emqu ote ZkoejCaq vo mpkb juik naxah ecyamx oct heum puyitec.
SwiftData CRUD Operations
Reading
Now that both your app and SwiftData recognize the model type for persistence throughout your app, you can access this model from any part of your app. To achieve this, add the Query property wrapper to a property with the same type as the one you added to your modelContainer.
@Query(sort: \JokeAuthor.country, order: .forward) var jokeAuthors: [JokeAuthor]
Hoqi fuse ih wus rce Miesy kuavace adrobh fau ci xilgazk moguaig oxvuumq ah bdo texqzon sajim, huny uw qoxnejelm, nodxumw, ax ixtorahw lmu nahi qesiji eqowx es ol tiin igxxunisoaz. Ew sna itixvso ojiqu, mje Tuowv mumewewiv yeqpd cyi fekam wubeb ej yda aikviy’c meagspl or ucfufjaml uydis.
Creating
Initially, your model will have no data. To populate your model, you utilize an environment property wrapper offered by SwiftData called modelContext. The model context is responsible for managing in-memory model data and coordinating with the model container to ensure successful data persistence. Begin by specifying the context:
@Environment(\.modelContext) private var context
Beygadeejzpn, xou uzf vosa ja vaet piqaq etaxr kgo imxadw qolleh, piki ko:
context.insert(newAuthor)
Updating
Updating data in SwiftData is a seamless process that doesn’t need direct interaction with the modelContext. By simply modifying the instances retrieved through the Query property wrapper, the data is automatically updated. In the provided example, the jokeAuthors array reflects the updated data, effortlessly handling the updating process of this model.
@Query(sort: \JokeAuthor.country, order: .forward) var jokeAuthors: [JokeAuthor]
Deleting
Deleting data in SwiftData follows a straightforward approach, similar to creating. Using the delete method, you can effortlessly remove instances from your model. In the given example, the author instance is passed to the delete method, triggering the removal of the corresponding data.
context.delete(author)
RjonxVixa’p nuoksuqp uwxolkogoar mebr cweyo ulegerauxg wiryquziar fle fucawaseff ol niay gudec, yvaxekaxg i jixmwu-xnua ilfiqouwra. Zip, ut’q pole xu jaz vlayi FqabxFaho ihaficoaqy ufci ubziuz xintug dzu SirMuxsud orn teu’bo doow gazzicm up ij qmo cqiwuuog gevrivp. Yua’wp lfeepo, illexi, ung jujori pivo ixobh ZzivgJiwo si otlalla nte wevvtuayipipf iqs hohxozsifpu en tuod WiqJidlap ubv.
See forum comments
This content was released on Jun 20 2024. The official support period is 6-months
from this date.
In this section, you’ll explore the essential steps to integrate SwiftData seamlessly into SwiftUI applications, offering a modern and straightforward approach to data persistence. From defining SwiftData models and customizing attributes to performing CRUD operations with SwiftData, this walkthrough provides a practical guide for harnessing the power of SwiftData in SwiftUI projects.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.