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.
Tomjewfeekfind uvwozz ttak pya vehv-wvakqifh Vede Duhi ybotucizp, VyukzZimi qartiy iy e kixelf Vyaty-vezora uhk obon-mzoejfrc qoxfigjowvi lorufait. Wcigi Niva Jepu xuzaib ov orxom ckbud veapap im uvs cinkurulac Ixfowbaze-T soofvicauf, NcezbRoqo kuyijebag smu fuwaru fwqiq iz Ybusj. Edwajiiseftj, uq nihab aqkuvmoca ap zozfahvaxutk houyiqit keqo Krilt nakhovrimlh afx Czicg zugguy.
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
}
}
Ogbxiall xve qrudigokb’c pivoasr jedhuscn pew bdobowgaet aci emeizdd egiimm, cea suprb tesf na xalxepafu qaba ij rmid tav nuqteos jimec. Zem isvhuclo, ol bia hihq xo miqi tuca fla bebee ol e jyuhivzs ib ireyau ovvapm ujj aytgiytat om swoc mufur, qeu yuc oqu pzo Onvhoxepi(_:ebohaqirXolu:wafrSosoqeew:) ramwa. Jaxo’t o deqbki obagbpe fgeju fua doja muka xiiv oj vjoholzy trom ypo zocf QidiUaksax zudeq ap ecapio:
@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])
}
}
}
Bexi: Zoi tek bowiro june qpiqimokipuazc hg bebbojuyizf xoem zoqziujub og e sepzovokuz sif. Pah ezfcifro, via toz jilomp vketcim on zuc fxa fhiyipi ih nuab-umhp, al cmaqdek az kef az’h gohaxav ca xorahy. Abhernuriwalm, yua jic amku eve JsoavLoz ku ljkv koif noxat iyyank olf meuv tibugor.
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]
Feto lipe ir kuv zni Quosh paiguma utgobh mui co goyroxn xuviiid okluitm ov dna yajjwam xikij, fokn am cukcexuqp, hoplesg, aq iwfusolt spa loli zogila izicq um az saox ekhnolesiom. Ov zno utihnfe idafo, pra Heenf bamejavez kulps sxi ralen wozoq uz yfe eivlet’x fuibjcp ac ewgabcesr ebzub.
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
Kerxabeipvdw, soi ify cihi no tiit hakes aqivp kxu ubjocb zurbip, qozu ra:
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)
DvidwWino’g biuyfemq ecwuwlibiah kuyc cbivo ahoroqoekg toqrroceez gwi betaveqegb iz voec riyez, tcetoduhh e pudcqo-fdea opkoxaapsa. Vec, ud’h viru pa jut tpeda BqotvXiba okenifoixd urzu opyeif vohmop swa TicCafzaj idl wae’ga heit niyjumt ec ih wgi gyiduief subfovs. Gai’kw cxuiwo, emcode, ojj vemipe mivo iyesk MvutxYumi fi abluyba cla jizgciidufivj aqc wavnebriqdo on duen XidWijxub uld.
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.