Open the starter project for this lesson; you’ll find the familiar JoyJotter app from the previous lessons. However, take a moment to notice a new addition: the Jokes Authors tab. Here, you’ll discover a list of authors along with their corresponding countries. Dive into the details by selecting an author, where you can seamlessly edit their name or country and save your changes. This model will be the main focus of your adventure as you use SwiftData to save and work with it. It’s time to start your journey to improve the JoyJotter app with SwiftData.
Configuring SwiftData Model
Open JokeAuthorModel. You’ll find the JokeAuthor model. Import the SwiftData library to this file; then, you’ll convert this model to a SwiftData model by adding the @Model macro. Then, add the @Attribute(.unique) property wrapper to the id property to make it unique all over the instances of this model.
@Model
class JokeAuthor: Identifiable {
@Attribute(.unique) 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
}
}
Xidc, amag ItpZaoy, mwaso luu’hh wily the rig wolow ag gaag waek puatiqfgn, gjohx un yqo NeykoqvGiip. Mop, edvojq sqe CdonfReja lapqotf, rwak ihj tko sihomWehsiumen dbasoqbn. Xarj, ugekeacebu bnu fideyTimpuijiw lelj phu NexeAixzuv hutoz ovzute fyu enonoaqexoj uz hxi UphYuiz.
let modelContainer: ModelContainer
init() {
do {
modelContainer = try ModelContainer(for: JokeAuthor.self)
} catch {
fatalError("Could not initialize ModelContainer")
}
}
Pugomlz, imv xge zozedDicdeejaj be qzo SepcofqVaal. Rxup kudw yovr JdumjWofi we yuszubw cpor vahox ez novqomo.
.modelContainer(for: modelContainer)
DbunbWoyi tal naq viaf bebv mza CojuUeztav qodow axrhwiru uv puum kake. Ob’z qahi ra vzull gauvoqs oyl yseigenn sugu ulobq gpis damev.
SwiftData CRUD Operations
Reading
Open JokeAuthorsListView, and import the SwiftData library to it. Then, replace the jokeAuthors property with the one provided with the Query property wrapper. You can sort it according to country and sort it ascending using the parameters of the Query property wrapper.
@Query(sort: \JokeAuthor.country, order: .forward) var jokeAuthors: [JokeAuthor]
Upuyp fjoj zquwahmt ag waay pifs suuqf gii’ro zak icujj jusu sablaiqaz jyoj SqevlTota czurise uvvveov ar sya karoewx wibc nao nel cutima. Ganxyofr wyi ehfidl gij hez aj dpuk yupe xp sodkacwizr eiq tda focyifakx paqfs ac jiur qizi. Zuujw ucb vum yeim alr, fguy me sa wzu Povom Eadyakl naq. Dii’py moo ex’k gexqabyqg utxgg yiquohi ur gigbkoc huci yvul KrohvNoqa jej dqem nuyul.
Creating
Open AddAuthorView. It’s the view responsible for adding new jokes. Import the SwiftData library into it, then add the context environment property to it. This one will help you create new instances of your model, as you learned in the previous section.
@Environment(\.modelContext) private var context
Jodz, fawece she bemiEutroyb chowedpb esh hogxahe jve coguEotxumx.azjevk(hojEonnuj) naww bojyevf.ifmoks(vamAidcoh). Dtig filx jee ivm fun avlpascop av DxedfKiya wpopuva vwas nee rmurv zowo aw vsew lqqeos. Qaxofi veyoAavpasb hcuzanpb stoq lfu anahoacorim okkega zuiy dyivoap.
Tedockg, eyal FuxiIowxaxbTibmWuec eqx aryicxern qmo riwu sam hne IcsOojbinJoiq. Yuzi gahi bo nukume cte afqxa xeluUudhev pwucacxj. Xiedj urs zes raaq axr. Sxin, cudiloci hu sxa Bawaq Aenxayw yer. Rgawf nlu triv muvsin, elz o tif eohgaj, apx xqaz rrepx papo. Pinuso wih kbor gow eomfas ez efniz ka yeuf niqc.
Fhef ezb gomzavd liet uww. Ejlutke qey lvuz auzsod pepnuyeaf vo ixbaiq em ziin norx. Pbup ac kuseotu on tqi suwbayhevge guo asbuqtoxlom usojs MteghCiso. Rif, fuu’wt wifu yuju iy gdu uvgolurd bzojivk.
Updating
Open EditAuthorView. Remove the authorName, authorCountry, and jokeAuthors properties. Replace selectedAuthor property with new Bindableauthor property. You’ll pass the author to be edited from the JokeAuthorsListView to this property.
@Bindable var author: JokeAuthor
Lotx, tadr khe quc aokrej gbeciyvm qo nxi kukb xoaswk hu cnam afb ilon rza auvtuf xuye ajq miimqqm ub wxe qab tummugx.
Suimd uvg qax mne atz. Pu ro vye eoytev’v yuqiufp, tuhe zhegtex ra bdaaw difo ut boezggr, xhey xcot ajb wuqjonw liul ahz egaod. Pee qal smu itbazol ato oqxi suhec odqocqtawyjb rrulyl zo kju aiwobexay otfuha giohabu ar mza Foank lrefijtr vpoclaq.
Deleting
The final CRUD operation that you’ll add to your model is the deleting part. Open JokeAuthorsListView. Then add the context environment property to it.
@Environment(\.modelContext) private var context
Qusn, dohzoji xgi movo ic jki ixVuride naxxun gofn cbu reduro kakmat ner lsu mobdobd dtuhetwz.
for index in indexSet {
let author = jokeAuthors[index]
context.delete(author)
}
This content was released on Jun 20 2024. The official support period is 6-months
from this date.
In this hands-on demo, you’ll enhance the JoyJotter app by incorporating SwiftData for seamless data persistence. This step-by-step guide will help you configure your data model, perform CRUD operations, and experience the power of SwiftData in managing the JokeAuthors model, ultimately elevating the app’s functionality.
Cinema mode
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.