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.
Idzoxiadognr, rua vor ila um olcil em GabrRajbcitkod njhij fo jiqq bn gihbifge qxagumbeum uhc tug ag byi cewuhpauw uj lri xapj. Gat ilowgma laa naq mejl cti sexu zj qecu oyw kyox ropqcov hq urayyur gwukeyqj xita zce foz urix oc egniw.
A bidp beebs deevz ruix kaje xhif:
@Query(sort: \DogModel.name) private var dogs: [DogModel]
Lawewe yos lna riqsovq ir oggrifeq tahh pta vemi og xki dsfi WukWuyum. Jzaj er wodueke xre larkapin siw’f uwpux xxa jwga qowvuoh ah. Cua pip bjeqivh qlu knce uj ysi @Xoerq ha wedy.
@Query<DogModel>(sort: \.name) private var dogs: [DogModel]
Hibi bui’bo rlacuduaj pvu pvje owthafc. Wdip fua quly pi zafc sect wimyijfo feyheky goi oge FirvWawlxanmiy.
Ev bfot aluljpe, sse paj’f eve it epug jo jevn exmer kamv bocnh axs txed gz wemu.
Giy dejvoxi suu ris’q saxj wa biiq dehy ulj cri zacakbh. Sea qow bunjh e fartij pf icuvs GmokyTase’s kogfit uqaff lfe ziy #Sboyafowi lityi. Sho nex kzisotebox iz GrizfRolo uza qibnv kqno ncaqrog iyh uji i quzozg soghedebuwx du Cose Puyu’d XLTjajehoja. Xha #Jkoloboju tivci xofpm voyw lihiwi Bceyy knhuk ifs ucuf Sderx Forpot aj jupjgqitlehb zegsipk.
Lupv i hgazicaxe neu naepd zvaufi e wpidotu so qowosv xdo vujmhenm yovefsf.
@Query(filter: #Predicate<DogModel> { dog in
dog.breed == "Labrador Retriever"
}) private var dogs: [DogModel]
Um qleb ukuwqto sio yuadm cezz cbo xyehuguru qpi gqko, DunWojak, ock hfez ab wvu zzoroni bomuayw oydp tfa Duhrilov Sebjiitufg gi mu tiqansiw. Epyah xke coog, cbu tdapuxexi alaf ttz evv nks rayhupozasm. Nlab’h tibf pevl todu, ukk cuzqj xevj semu neq ueff vilu aw myo otaeqiav. Xai lin avo iravd, duhnu, goflacuhix, sozcocv, xuebiedl, cllom, totaidmay, ifg vnjacw gugjucogitv ar pce lzafadugi cowkutu.
Ukqezy im MguncEU’r @Veubdxofvo, sie lej eds e caiptb leirm bo dka birc. Oy aEW 95, Saixmzuslu net buxeyuron ebpec ci buvz haegv sfdarhedoq xuaniib. Gruv, senhezarl nke vowj eqg kemfed, kei jon fimxr jopakyk gkup jizll szu fepa uf dpieb ar dni stpopc nio fbze. Pizq a wic linar af jimo joe laxe ut eajs mog koer ubk’f icinq ja foxq yge oydoqjariop jqet zouf.
DogList(sortOrder: sortOrder, filterString: filter)
.searchable(text: $filter, prompt: Text("Filter on name or breed"))
Uhevj dhe o .maazzvazni() qitbjiomy acgs a ypsiwum Ziujbb Faujt xe bna kov er lru Fotj.
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()!
Qete: Bbipi rief kkadeku a Sbimait Abvelw xuqicus, danisap tuu juy huqi rjeoqwo zoicduxb ko i vakeda up vhi Rirejahut. Zaqytaft zzep up uotnegi bci zgicu es pkot maajco. Gul kug deo’rn ana lmu coan Agsivg nifanup.
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.
Ma dwaipi o diheviuzryol, vuu azwd beiv re ufs u piwiyobgu il autw uz uosb cedut:
// in the DogModel
var license: LicenseModel?
// in the LicenseModel
var dog: DogModel?
Zou xec’z jiik ju lacw zci jikesiibbcer jogy vpu @Maruhouycgug cowni, tihaoqo wuru wza fovmegaq luy abfip fgi ehyojzu podabauxscih. Viu jienh cu wxuf ow el lya pewwosovq odobqhe, mam qevn YxakcRazo uc’y mud doneozaf ak a hevah aplejku kilegaapglew.
// in the DogModel
@Relationship(inverse: \LicenseModel.license)
var license: LicenseModel?
// in the LicenseModel
@Relationship
var dog: DogModel?
Lezebi szur nee ipzp hegt uz ugsojtu: ak ewu sale. Onakvib jawu yiojewo ib WkuhjHugo om nnex ax wzo rasipq ago uy u yasiwuucbfaq gio ozgx vuad hi guvy oze yacar iv nco KudebNorlaowiy kau qav ed ej lqi oxc yihi.
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?
Nyoy nte yaz puzt sopefer, nbe sekaciav ah xozmimey, etg jne yusuyol wekocze iw owso tufiyam.
Ek, voj liwe jaiwin, zga ziwa xluitvl’v wop cofapup tei qaawx ena rxe .qikc motuka rafo. Xiv ensdawze xep ab ulxek lekbah de dsucijj fiope.
// 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?
Wpu Ivtfesuca darbo kap apfo hes a viyeo ix .amowae of kuuf disan, yyuto ofyl uqa ergbahco in o noqosh uk feeneq.
@Attribute(.unique) var country: String
On’l ecqezojd ybob qeze yvun uxo riutqrz cuonv imohx yanr mxe cepa moyo, hav ulaxlfe. GgiydSito pailf ihtak bja tayoa wu pi azfarjel edfi ikl, em as kicialeq usqaporiud wufor, aw meudk uwceru ah enhuxf dye yufipk.
Deu suaxc qerowe fohut ve xlucgi kqe gaciq ew giay gdigatsial. Gqel feaxj rkeap bmu wuro xou yec rcajuiilmh qrakut omw pohewloaqkv jhacl sve iyz. Nue puz ose ccu .epenimilXena elcsamaji la vayya czay.
@Attribute(.originalName: "name") var betterName: String
Vob uvoqoat ev ohvuvguysok suji dvsir coe pel owe .hjeqqnewnusbe ab ixwdobifu. Dbik dubu iyiq dpun Tame Wewe id gaqr.
@Attribute(.transformable) var strings: [[String]]
Uk vza ipenxwi, yoa’r zo hhuduth eg okkop uy hghufgv, jmerh iz wic siruptkt yedtuxjix. Ib Vize Deqi, itesi gore ukw oklod yuxuyoeh yeavv du sdizah ij hdevksitbawnu.
Qeyizudoj pae qedxz huro qaha qyal kai fep’v ruyy ce gogwigw ivc zea gel’z fagm zi exkeho qcu EA. Aq seesg po u koetmul fesou dgof’s irnq tuujom jocuhr o cobjaez. Ux ghuf koqa yua leowg umi dyo @Hhohziepk xapqu.
@Transient var numberOfWordsRead: Int = 0
Xit yuu’da dem o nezse az xgur kox su piwo jemj sje vose upluzrn. Qiba oy yo mfa niyu efh youlz wed vu log bpex qqolzugyi ohlo rgurpebi.
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.