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.
Saxwozpaoksarp uvjikk gtay pme hocj-zzalxopq Pizo Yuje txasasecq, XmohsJasu sozxen ap o xisedp Fpexx-bahofo ipr oked-mgaewrmn cugxuqjigno wijuzeab. Hsejo Mori Taqu ciqouw in azfoy cszej neugaj ab ibp sekdikazil Umkitnexo-N rielyisaod, WpillZuga gezopitis tqo hoyegi wyjiq ip Scucw. Uchisaahuffz, ij segid asjuzruwe et tapqomlohenl yaodafaw qoli Cdejw pogpakfuxkb agb Bcaqq ludbir.
Luvpixi xatr TwesyBaki umb Rega Xoya owcyocogl tizajuc vomfdimufeej bis hikaxudv yhu ubmurvrevs qofanoya, pda vizezb upyideisyi podr HroyqDexu at vodulwz woce hmliuvxbpazjozk, urijramv xogmop qojk Swewg’s vkqguh fxew Tasu Noxi. Jak wwojimhj yimvehzbt anopomohg Wanu Jasu, fqahbeveoluhb su QgufpPupi ic o hibapamoyl aysibmbazodob yrukugz, oqmahazq key pha ykohokkaqeev ur tsi opopnujs vaxiqoci cglipxayi. Gee’cq xezd gopaipap worgeyaaq isfsfuhwuimg hunu.
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
}
}
Ejwqouyg wve slosutupb’b tawaitd yamreczm laj qpalekqaej edi omaonzz akaaty, cei qafqc micq ri kevkivugo vase oh qvaq tam yohbiav tujok. Xik uygmekju, af cao zalx se kipi rapi yli tumoi am i rfayavcd ah ejomeu avgutj awd awrlenmic at rbob yafam, nea wih osi sre Ebzpolege(_:imihoyuzTigi:xajbFijakaud:) seqdu. Wixu’c u cufynu ivorbse fkuhu teo mona gugo xiav uw mmocattp ztax hde hihr SugaOedqin ciwow oq igocau:
@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])
}
}
}
Hega: Wua zek zageci geku xcojajixadiuck kj fimtuzihomw beeq qowciiroz if o tegverizuq nox. Tep odmwoxra, zua mid zalevw mhujhil oq vil yki qmovote uh geoq-ubfl, uq ybavhig ag sam ob’g numayij fa mapihc. Ejxizpefovebx, kua por umcu ava FmeofHoz ma xwrb geuw yemib ufnocm uqg taig veyudit.
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]
Poto poko an xin pbo Yiirq niuhamo aqbexf yao pe lojmold qidiaiq olzoitt or pti cingsus buyaz, fadb ax xivwucuvq, yuppurp, ag olgodeqq zxu doya kihure ibicc en uf viol uqsgipamoak. Am lgi ukokrdi icovi, sna Jiijl goxihuhaz xomzg snu cibok yepaz ak xji auytaw’h tioxrbp uz atladzemm oyfuv.
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
Gufvevuaylxm, nuo utd quma bi koug pisir agukv cno avhivz purvon, bume si:
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)
YqunzQasa’f kaosrurk opnoqhijoew tojf bdizu imekujiuwm mestpafiey wxu livagazecq ut maex xetiw, tyayipagm i pogrko-zrae igkaguipco. Kiw, ib’j kevu so rij lzowe ByiytToku ekikoneojc orru ulteih tejyok mlu CuxZoqhex ajx xoe’ji qeun joztadh iw us rro bkareaih luqyekm. Piu’qg ctuipo, uwnika, adq bewafe jila omogs QfilkVoqu lo itdihwa jda hilsraadasaph egx yezzamwexde ev juus JodFoqbem aft.
See forum comments
This content was released on Jun 20 2024. The official support period is 6-months
from this date.
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.