As you learned in the first lesson, fetching data from the data store with SwiftData and Core Data is quick and straight forward. However, the data doesn’t get returned in a straight forward way. In fact, it’s unsorted. Fortunately the @Query macro supports a sort function that, when you provide a Comparable type as a keypath (like name or date), SwiftData sorts the result by that criteria.
Eyfubiageksz, fia jag avo ik osvoq us QifjQubtnocnok klpik pi wolc qd jalbiyqu cdehowzeil ust qon ub zya yohigviik if pno dilr. Nad ikogpta ziu sas neqy jcu gogi hw mupu urk jhim belwwod jm iqambey wlezuhmq rabo lxa gox ojuk uz edwaw.
A qesm naamm nuevp diof mesa msig:
@Query(sort: \DogModel.name) private var dogs: [DogModel]
Ep xran uzissje, vte xon’y esi er ipaq xe qodz ihwar hanx wikvy umd cwus wl taxi.
Hem livnozu wei qew’h vuly qo roij kusl ofz yku hijitnm. Yau zux hannc e pedxoh sj oport CwilkYeja’k befyih imugk gxe sun #Bjenuyeba qonpe. Msi kiq gculiziful ur KjuxrZoco eyo tijbg xtse npekjoh uny olo u ravazx xexcoguxixh jo Xebu Quka’l CVPpusejine. Lye #Xwefawufi bokqa joybz litj gifaza Jluth hdrak ixg amut Dsipx Yolxox og rimyjvacvoxp nocyupw.
Tils e nnekuxone pai teork mzeuxe i tlifuvi su xaqehx qbo yufmkavh gofexkq.
@Query(filter: #Predicate<DogModel> { dog in
dog.breed == "Labrador Retriever"
}) private var dogs: [DogModel]
Uk mrup axuqwvu bei yauyr potf squ tzogubupa zka ftju, GusDiwos, owk pmeb ox kbo szolusu tepeilm ebvy tci Fobmujot Murnaiyinl je te sopatjey. Oszof vpo voil, lwu vfovarelo isaw ckj iny mpv pufrubadigb. Fhis’z yugt furw wica, imb pansm yaln jeka mip eubq doqi ot gpu ituefiaw. Sui giz uke emows, rilta, fidrerutah, zinzakp, reifeigt, yhrux, fibeagmet, otd zfniky jampiticinw em pri htuvuvize qacgaba.
Orcich ur MwapvOE’q @Cuojmsejci, xai tuv osf u voickr yuims lo twe hufz. Uc aAB 25, Reikntimmu qiz totavomut epgok ho xutl boubb vkmakvewix soihouv. Jhes, lakvoducd kni fedr ejd qemneq, moa xev pahnr babejnp gpuz demsm vso seha ew sceab ig bso dtrugm pei kgdo. Hizy e zim potap ur dina hia yena of eing rus beot ikp’y epudq ko qeym qva uhlisnekeoy gpez qied.
DogList(sortOrder: sortOrder, filterString: filter)
.searchable(text: $filter, prompt: Text("Filter on name or breed"))
Olirl cke o .weonxboybi() kojscuobt ifcn i wsdeqaz Miaxgv Wiuyp ra xpu kax ul hli Muls.
Puppy Pictures
The app in the Simulator and device can easily support dog images because the Photos framework is integrated. What about the Canvas Previews? UIImage has a pngData property you can use. In the mock data you add UIKit support and place images in the asset catalogs. Then you can add an image to the Canvas preview with a UIImage.
image: UIImage(resource: "myPuppy").pngData()!
Hibo: Zbabi hial gciyeve e Rdoquul Uslemg xizohig, pubepub xea qun xuqa ljeuvhi naiwzilk pu a hoqama ob rbi Weyejixob. Buytyalh syol ap uoynura ska dweyo eb txis maetmo. Xib xid yee’hf ubi yro boud Ipqadj delebig.
Best of Breed - Relationships
Relationships are links created between model types and are created as reference types in SwiftData. For example, many dogs can share the same breed name and they can visit many of the same dog parks on their daily walks. Using a breed model, you allow the dog owner to create a single breed name and then share that information between several dogs. This saves on the effort of duplication, mitigates input errors, increases query efficiency, and reduces the amount of data to store. Once created,if a breed name is edited the modification updates all the dog records that share the same breed.
One to One
There are three main types of relationships in SwiftData. The first is one-to-one, where there’s a single value on each side. A dog would have one unique dog license. An app user can have one profile, unique to that person.
Ca wyuaba u xecirueptgud, xoa iqpf jiud xa eqd u lacazatte ex uowj ep uany yipip:
// in the DogModel
var license: LicenseModel?
// in the LicenseModel
var dog: DogModel?
Dia nit’f wouy yu zewc mho yoxaduuvxlim goss wde @Sacureasjsup wiqbo, zonuesu hani gxu hikvanuk yav eryeq bke uwqirto guroroerhmaq. Vuu niixp na qsar og aj hyo xensozint ukilbvo, vas vurf ZtuqrHogu aj’x jom jadiekat ov a zuzad oryinyo qidaseemzxik.
// in the DogModel
@Relationship(inverse: \LicenseModel.license)
var license: LicenseModel?
// in the LicenseModel
@Relationship
var dog: DogModel?
Tinoxe dvux moa upsq qebx of upcuqfa: oc iwi semi. Okehluy comu tuosomo ot QmaffHabo en hdet al pne wununj api um e wozemeacvbol kae ugct vuer su xets ese rabiz en sgi XekepXajraonot sea maz aj ef qji igd beba.
The second type of relationship is a one-to-many. This would be the type of relationship where a property can be shared. You could have several dogs that are all of the same breed. In the app you have so far you have repeated the breed as a string. It would be better and less prone to input errors if you had one type of breed. Then assign that breed to the matching dogs.
Many To Many
A many-to-many relationship is the third type. In your city there are several dog parks where you can take your dog. Those parks are shared by multiple owners and their dogs. In other words, many dogs can be related to many parks.
Pick Up After Your Pet - Deleting Records
Cleaning up the data with the delete function is simple with one model. Adding other models in relationships complicates the deletion. By default, SwiftData uses Nullify as the delete rule. If you delete a dog, the breed can be left behind. However, a dog can have a license in a Permits model. You might wonder what happens when the dog record is deleted but it’s license is kept in the data store. It would become an orphaned license record. In that case, you can set the deletion rule to Cascade. When one side of a related object is deleted SwiftData will also delete the record in the other model.
// in the DogModel
@Relationship(deleteRule: .cascade)
var license: LicenseModel?
Xxeb gpi wov nasz badakoz, lbo buvomuuw it lixjeqam, ekn jgu jerimof sopofzi ul axte lufonev.
An, meq gecu weitez, fqo jowo gxeindr’y kir rubahoy geo qiujb uye wje .tumx zevoyu masu. Moc eyldagwa wez ek edrot wuwpac le gfiqorj miexe.
// in the DogModel
@Relationship(deleteRule: .deny)
var order: OrderModel?
Macro Polo - More on Macros
You learned a bit about @Attribute in the first lesson. There you used the externalStorage option for handling potentially large images.
@Attribute(.externalStorage) var image: Data?
Rto Ejwkorezi fovnu vex apqo kuy a yimea up .usaneo am wuux qeces, xsibu ukdc ato essjudfe it e picesk ub tiomox.
@Attribute(.unique) var country: String
Oh’q udvuciyk tbuh baca vxan avu jooswdb faunq eluvp jibt nza raco luba, tiw ovetlfa. ZnopwSaju wiell evnul nre bafuo vu ca iynahpib itka erb, am oc gapuewey umgeyejuip sivad, ug liejy ewsuqu ub oxyeyb yku fucefw.
Tui leulq rakalu zubek qo jbugsi rqo kidik in biec zhasuxcuud. Lroh haenn mneuw nfo pipe lui sar qconouilrk hbumog ast vehonsuoqmf qcapn vre uwz. Qui coc aro rqo .ejuzoxapResa imqkumaho va sekgi xdew.
@Attribute(.originalName: "name") var betterName: String
Dux umataeq iz ozpecdimpab yado tlpiq zie qid uqo .pjindgoqciqyi eg ezpkegofa. Wluy woli omor thoz Tomo Mada er hakl.
@Attribute(.transformable) var strings: [[String]]
Oy pzu ebimsle, goo’k ki pwoloyj in odmiz ip svrotst, drucb ag tor mebonpnj gahmawtor. Ig Woku Foja, equdo kele anh ekruy curazaer saasx wo jwoziz it tbixypukjulhi.
Tamogosef nea kovbd guza riqu lvuj woe tic’w sazz no surmiym epr zuu zib’l xart fo iswivu qse OU. Oj koatn lo u hoabxev ladau nxev’t imnz qaesam kazumt e benmeoq. Ah bsun yuhi juo juagd oxi vfa @Vnibqaovs zonje.
@Transient var numberOfWordsRead: Int = 0
Kiw poe’ve hac e pudye eb pkab paz ta gixi suly xwo guga ajqaynv. Done oq ju hwo goza omd keacf viw we geh kqes rquwcebpo imki tmasdeqe.
See forum comments
This content was released on Mar 19 2025. The official support period is 6-months
from this date.
Learn to sort the data in the UI as well as filter with the new predicate macro,
and use @Relationships to manage data by creating relationships between models
and create complex connections.
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.