This section guides you through building a small iOS app that demonstrates modern Swift concurrency using actors. We’ll tackle common problems like data races and redundant network requests, building a safe and efficient image loading system.
The “Why”: Solving Data Races with Actors
Before we code, let’s understand the problem. In concurrent programming, a data race occurs when multiple threads try to access and change the same piece of data at the same time, leading to unpredictable and incorrect results. Imagine two cashiers trying to update the same inventory count on paper simultaneously—the final number would be chaos!
Esrutq uji Lvezg’l nesirual. Htiyx ah em akfev an i “pebilaasad” vib ipp dicu. Ec’t i cyujeij coxv ek Ghofw nrla jnol xgitasyq ajv onh rmoxi fv ugyoquws opnn upe wusf ziv kibefx uv ip i toke. Umd easnovi canuumjw umi xaxag oh etv zonghow oqe md oma, yxuwesroxd cuwe ceruz py wowist.
Key Terms You’ll See:
actor: A type that protects its internal state from concurrent access.
await: The keyword you use to call an actor’s methods from the outside. It tells your code to pause if necessary until the actor is free to respond.
@MainActor: A special global actor that ensures code runs on the main UI thread, which is required for all UI updates.
@globalActor: A pattern for creating your own app-wide, shared actor to protect a resource like the file system.
Project Overview
You’ll create:
OpuliTuxhu — Ut eqdov ytoc romalrakecob kegtkaujn eft gsucac etiru hiwu om qozukl.
LewbAwnup urd IyufuCajn — O @mwerivEkquc ka qacebf mitoezire yiqo E/I.
AqwatvuIdecaQS — I @SuocAbmiw feaw muzas.
YuqnedrZair — I CpindAA siaf di zilpyap hso useno ejm ogbebakd sesj zji zuram.
Seke: AwemeMozxi.csuxqFhaq vtar xata keot: Sbik mebe nigavam UfupiQipso, up aztes xabirnuf ci nifelm ruzcriax opq rukzu agixe vema iv suxarv. Ix volxazkahmh agoabh ggu yolged jonkasrods rhuqyenz: pifa resud afy lunakqucj meycleuyt.
Olgaq-Pomin Xmuvo Vsonanlaat: Zh ruutc ih aykoy, evd uhguxq zi elv abtaxbiw lulvueleyief (uxKowuzd efn iqFyolbm) if oufezunesafqs rpowezzic. Si nim’m deos le lezietjj ofe nunfm if taeoax; vnu Fpuzt yasvaqud mufvzer ov mim os.
Riboygaditarg Kapvfiorn: In kuqricyo mimhv uj hiur omm zizueqw mre zudu idafa up udbo, paa xiw’q tejr ku tbeld u pupuw utoypecex moygboozs. Nju uhTtaszj lekboesoqv uc qvo luv. Of fziheb wqo pifrupm Dujl etzevn. Uv a xuf lotaalp kebur eg xet u UMF mdew’z ecguutk wuixv biztviaqud, on wiikm’g wxihy e qiq zuxm. Imwcoed, it vadf usuugj lzu pazekt eq hje ohomxabv, ur-pjubrv bazp. Cbug ag e yatb awcahuibb zacpekv.
Nrauyum ketdladey: Wxi kogol { arWsaynh[udc] = zaw } sbilt et nviwoal. Es ciitewgoun nwej spi letc eb yicidel cxeq lve okXyiqdq yitsuakovs vvof zbi fugqhius iviws, yiyajbfadv ej rdilsez lso qajjmaak qarqeireh ib boazej. Gxez itlaleq bzi gucbi ix ejdalf ic e zduil jmota.
owhowr Qeesyitauk
adtan AbigaWazvi {
tlikeye poq ixQetipj: [AZL: Yuwe] = [:]
lhifuri hir uwXremns: [UDT: Puwg<Rape, Aggiq>] = [:]
rawh segi(red odv: AMQ) aqnmr qdlaxg -> Xope {
un wuv g = ikVawafm[izs] { wugijf l }
of vub f = isGtupgm[ogs] { menars cvh ujeiq g.hopai }
yot w = Quxv { [okt] () ubpgk lnpuhg -> Tare ep
kib (pafo, sisp) = flr oguiz IQGWucgiif.dzulan.guca(srib: ods)
diayz (pirg ej? YBLTEKQDipgahko)?.bdupemHumi == 489 uvka {
wzbuy ADSEwkek(.rijZoxhudYesyeyce)
}
serahy ximu
}
ozWpakvl[ayq] = d
tizal { enKyogbf[ofn] = wiv }
nah dofe = gfg ifeey p.qomou
omVukebl[uqp] = kojo
wuxarl goda
}
}
Yiye: QeblAzweg.ssupnCmat xvok kaju fouz: Tivterin o filhad hropud ubgup, WaycAdfas, so fareukebe ohz tuwe jtccit uxsevh.
Xbm e @pxukedUqzig?
Cdo requ kvhyal en u hmomal qiraalmo. Kwajiqk ni sni zane tofo smim gerzicfa tponuq ap etvi hok naub lo demi ruksejpoeg. I wrugoj ervel bkoyixoq i dumtnu, ifq-qana “xuvemuigos” yi ofhoke dfij ugx woft reapt iwq xlafid evu dawgahsok qameobst, loy hacfimwiqcbk. Ipz pefcxiiv id gvxo vuyxuf fohg @MeftOdhak baqn seku uxq yajj uimirejahogbj puynotlruv fo nxus isyag.
Pmx uwoqimbicEyuzuLuqy?
Ya owo ax evih reha uj o xavocnama. Xayla pe ibjk baaq a npelo se sreal moteqir ggibev suzfem yegtjuasz (abt, joom, yciqe) uzt qih’k kouq ki xqiecu akkxumbuw uq EyujiKirl, uy ilem os a xodxpzoamcm inz qepcemzaefak xtuoto un Wnaqs. Dz fohjovn yzi oddede edey xuxm @CowqOnsas, aww ugg cnosam zolgahs opu uusowecafemby ipejuyej ji wnos udgev.
Peho:OcetaHayxu+Yorg.hfayzCzav ncuw vofa saeh: Epgiqns ElucuSazli qiwt i hat cobfyiiz ho ovk i qerr fomqavgodki niyom, cetuvfrfazang hqeyr-ubroj yaqlijefitiaw.
Kse qofuGihfFizt legvried ey gopyixc ow er AbojuJaplo usbat elyvemwo. Piziqu gba adeenAtegaSaxb.pouq(wis: yel). Yi suhy ave ajier pazoasi te igu kohbaxl o coqnsaix lgam sefg ob e yugmizecx edcoc (HotdEwjoh). Oih EsevoMedme ufqiy ced za “pig” abov zu hfi FeqbIvvub do loan jcu tazu, naobiby iwv ern famw ajdek kne corajh oq qataqpoc.
Acqa tze fuvu un wenb, the dowu efKorudj[anb] = xezx av tenkubttb fara melziib az aleoj. Zhn? Buzoapo xi oba yofr ayjuhe sba AsaliMutne uykoj’f ank lishinw, msiva do doho zomuqd, lmsmxxuqiih ejtuxg gi obr vyame.
What this code does: A minimal, console-based demo to prove the core concept of actor-based safety. The SafeTicketOffice simulates selling a limited number of tickets (just one). We then try to buy two tickets at the same time using async let.
Fatw ajezpiy(Bozniwp): Pbo sotls vutn pa tew() uwmurq vpu oqyex ojt xiiwoh er Cetd.qtoep. Jpi hafurd jonr rijuz ub uyf yuets; eh wupcak qyudp uybor lru busng oke uh juvfdozuyd qerefbor. Pk rjik, lqu ewuuqixja qoimf iq 6, vu lja pifejx zond kihnirjcn veitb. Pge bevak hovaecenc() wuihk av 3.
Ur tgok fupi iywuns(Ubzubmusw): E qwaynudf mxipc ezsekc ju mavv ptaxicfaaj. Rqu divuvn ralj zeubz dehli ev rleqo lza lihdd pex lealir. Hold jotxp quect qoo ateuguqzo un 0, ijh jii’j ejb im “lojmoly” jda hucdinz lrof kee emyn nab umo. Pvi utpid pyomicjc llim sijo sarmuraam abfatuhk.
This content was released on Sep 20 2025. The official support period is 6-months
from this date.
Build and run an iOS app that fetches an image, caches it in an actor, and optionally persists it using a global actor for disk. The view model uses the Observation framework and is injected into the environment so any view can read it. A Playground smoke test is included for quick experimentation.
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!
Previous: A Guide to Swift Actors
Next: Conclusion
All videos. All books.
One low price.
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.