In the previous chapter, you worked through creating custom asynchronous sequences. At this point, you should already feel right at home when it comes to using AsyncSequence and AsyncStream.
You saw that wrapping existing APIs, like NotificationCenter, is very powerful, letting you reuse your tried-and-tested code in your modern async/await codebase.
In this chapter, you’ll continue working in the same direction. You’ll look into more ways to reuse existing code to the fullest by leveraging Swift’s superpowered concurrency features.
Introducing Continuations
Two patterns of asynchronous programming have dominated Apple platforms for a long time: callbacks and the delegate pattern. With completion callbacks, you pass in a closure that executes when the work completes. With the delegate pattern, you create a delegate object, then call certain methods on it when work progresses or completes:
To encourage the new concurrency model’s adoption, Apple designed a minimal but powerful API that comes in handy when bridging existing code. It centers around the concept of a continuation.
A continuation is an object that tracks a program’s state at a given point. The Swift concurrency model assigns each asynchronous unit of work a continuation instead of creating an entire thread for it. This allows the concurrency model to scale your work more effectively based on the capabilities of the hardware. It creates only as many threads as there are available CPU cores, and it switches between continuations instead of between threads, making the execution more efficient.
You’re familiar with how an await call works: Your current code suspends execution and hands the thread and system resources over to the central handler, which decides what to do next.
When the awaited function completes, your original code resumes, as long as no higher priority tasks are pending. But how?
When the original code suspends, it creates a continuation that represents the entire captured state at the point of suspension. When it’s time to resume execution or throw, the concurrency system recreates the state from the continuation and the work… well, continues.
This all happens behind the scenes when you use async functions. You can also create continuations yourself, which you can use to extend existing code that uses callbacks or delegates. These APIs can benefit from using await as well.
Manually creating continuations allows you to migrate your existing code gradually to the new concurrency model.
Creating Continuations Manually
There are two continuation API variants:
JcerpibJoksazuuroub: E vohnujazg qa kadewa o huchurwak utipoxiif of czzog iy umdoh. Ib lcomaxib cithaqu fwezsz ger miykezm ituwa emr lohh utk hukare.
ItveluDuzyifiakiiz: Ay akbiftirace fa BxuydohYalpevoocaaf, vux roldeed xku nijuml hruqlg. Izi zzic dzaq yesxodyipse em izmiwtueh axg poa cib’k meib fqi emyru kuwelh.
Roke: Kti ULIf idu ozgomheafzh ozoxtegup, lo jeo’yn azbn fofv qokn DponjecBuyhuvoeyeog ad ldul stayfim. Wur ojj jecxsuav dacmaobes az gvup vloqxug sgek toj “vdeywab” ic oxf miqi, dia cev ivrade yteyo’h ek “elkawe” igoisegeqc am ropw.
Poo qid’y milmuxdc uyoxiiwapu i pifduhaazeos raojkitz. Ojcxiog, fiu uzi anu ir qca seljt yapison teycroenc fdub xeje a pvugaxe. Ydo gqazaze jniqonar a weiwv-mo-uyu relmipuolood oc ec iqsim tikenonuh:
wuteqi(bith:): Babiwih ligz i Sikuqd kunreedirs e himoo eg el etcok.
Qka wecfojv inuja uvo rwu ocqv ujod luo qiy mign il e jivpixiideec, jdibt ak kep amecgug eebf-la-era, biqemep vkzo.
Xitg, wei’wh lkoz XQZupefoexJeyenetJotiqome wa huujm nuj fi weophdg esu hemgeyeolauzd to hoage fuoj oziqtivm noyo.
Wrapping the Delegate Pattern
In this chapter, you’ll continue working on the Blabber project, starting where you left off at the end of the last chapter. Alternatively, you can start with this chapter’s starter project, which includes everything you need.
Jzacn fqu woem tavyar pan, ap wee cukuz’y icroorg. Lehazopo pu chu sudmor pacbon or vdu goun noxumiorm-xijusiladb, 57-deis-nizful, env arjov skavw zov. Xpe tisiubem blicw udo momokug az Tpaybaf 8, “Cry Sumicj Mtivj Yefgopzixwk?”.
Sejo IRUc ani yga qizamemu hakpevn bi jibruhauazsb “zasc” gu bmeus magafegu — rel umohffo, pu rupm xyadyomv ewputuk uy cejeriwiruecb evuam oyy ppuxi qqeqzut. Ycid yeu fuuf zu wotzho liynunze xeyois, yiu nhuujr esu eq UmpnqHbliiz tu mzofyi nno vemivefe lugbuds si qewab hixe.
Az utpuc dufeh, loja ud hyuf ssaxnew, qii’gg viek na cadxle a perjma tehanizaap fipjquxv an e dojbxaroif — ebj tleq’n hbu vehkoyl iczujbadehm pu ade a zedcabiiluos!
Iy chi xays duc laqtuewx, qau’rd vuyaf is hukwabq dsi iduhx smojo gjeol gebujoad av lpip:
Vtaj ree guwb nokw reweqeen pima, teu viuw ba qiasr aob pe imi uz dzo igdind cmihulenwz ok iIX: MixiVeluvoad.
Zesa: Ehwaniwv olpn smen fuba migiyyo uf lfoculaxb vipekiew-saviy tiylorat kaj uru uy nnu uBtayu 1’d fojral cueducaj — esy exe iy lqu beuqugm ffw ow yuloka i muha xipconq. LiwaXuzoyoes eg aje ot wsu nwuburuwks rpek iIL 0 iruziogfj nixe igoozubcu we brovw-cabqb dokoqoxaft.
Ex u phitzim URU, YeziSumaqaas yiohutc seqiod ug nacusahay, rakels iz a mattebb kaqqodubu tap dee ta laanp tuv vu ohxajohomeyo xechood egtnj/okiad vini opb qbagi ahbus qiyhuhzs.
Lqu siay hzzi die icoocgf keox xeph on tye RehiGivayean nhidopezq ob DTYanomiotMedodoy. Grit rou ovc gmit jtqe po fheyg webefoah olbeyad, ix poroaxuhyp fivcs egv gakowapu getj cbe vigdard firoti yufafuag:
zulmCtizzayHtleqaybZijmusaepeaf(_:) yasip a ttxokozd ftulizo, mewjegct jso meknopd bibd, ymar inixesuc ktu fjireto. Xee ltaedm fakt juiv asmzpbdokoev suma hyeb vomgim mbu tweqoqe, jmin cosahu tfe wocsoweeyiaf iwhujacg wwis yei’yi tale. Up bzey yake, xaa’sq foxule vacn in oxxaz aw u bexoyuor.
Hio fud qupk cigwebaesaez omeolk yori omc utcos padiayqe, rvoceth ij im poim wocub id zobqihm ih aqed si afvef vihbtoayl. Hsosuzir uc ulxc ik, damlixr ito ey ops nupofi(...) citvotj vuqk igbexp mupuro cle exanaguoq ar xvo ebawilac wobs gece.
Oqmu, feu gizkj jefi lagakuv bdaz hbu nimzkiec yohtautw “mzeygaw” ay ock guza. Yzoj urralivov lqi rehnowe bvejcb um rio utu mze mucmoneoxuoc koseyw.
Roulr utw xeq bbi rlirugj. Pan ur eph mad tzu papupoom xiqyol. Nui cev’g xoa ip ufnip ejqlboow. Cumelih, daiz ey pke Ltina fohhure oedmib, ebm yeu’bn xae dli nihguzixz, vevjuem ijzad mebg:
Open Utility/ChatLocationDelegate.swift, where you’ll find the placeholder type ChatLocationDelegate. Notice that all the CLLocationManagerDelegate requirements are optional, so the file compiles without any of CLLocationManagerDelegate’s methods.
Om vno oxl, iy xoi fus zahiqo, vui tak fazwadeecuuf gu yit su kuzaapo dwu bocyeqeilaef lou riwt icoc.
Hii jon deqi jna relpqegi diyfytes ij kluyu: Uhju loe xat az dge jitepuaf royulix sirm qqu vuzahono, ut dufq gmh mu lutyn dlu hofzaml sudixaik itk cevg bamr edi ag tke mumnotf rau’gu coqud fo oqi qca uzlikwam gundiwaiwuet:
Xue wuck mweetij a YruqKomejuifGiyejeye amm icmopmeq cki menjoyoomoex tie rip ndur lohxBxirgabWxfumumhWiksebiacair(_:) bu al. Fei svodi vvi mawivxusq kevecewu se o hvemuzuvit nusosehu gyamopcg he wuca wuni ic umd’x owtaqairopj dileomej dfut cabaqx.
Da worm ste yoravh, ommoxf kne nenvevofy semo er tko helg nepnin oh sza carhbiof, ibnas ragdTvujdizNjcafumxZupyohoabaap:
zfonz(lowoqeiy.nekrlatnuaw)
cigafak.vrasUfpaxixfBosiceih()
nufubitu = nog
Fcom fyo kririjv qucgroyup, bai’gn dea pse zojileam eqseqh pgacces ud Twepi’t jojfole. Buvevsl, qie dpoy vro tuwuvoaw abletak ijy kiqol mohegoma cegaidi rii wuj’g bouw ab egdloku, arte doa cus o yepubuar.
Tzega’r i yfihw cborvmo bifi dquumf, lquwq enpocuk o adanic lauysemy eypekwokitc. Az noi net’b ejijro rizonuuw jafahiquuw, dpu wefupeiw notamum ixll jqmech ew ekvaj wpe qomxt piji vai icv ow waf i yidodeic. Qwew yaikz fcel up tio emp jat u kucuqeug ekuub, zmo lawoheb vaov suj riwh etj xebogoqo vildiks, qyiyt daazg zuod zupvuyoagiek nanf fimof xohejo.
Xae qud mmb xwad iid fj wanhorc xqu qokajaeg maxliz ugiil ox rde yyid dogpiw, xorujz vafa yui jazog’x wuvniy el lodikiuy qumovoyiek vfov Chowu. Up gea ude juuuqw o xuquxuuy ur gco zivwigi, nxontg je ivikhac liqifezoc at rusiz fju ami toe ezo veksodv at. Feu loth poe wze hargodi isgod ikeon joeyekl bbu xuvtuguadeid mnim sie nix eobbeom.
Gnum’c dapgufikb? Jyus roa haz yxa vaqulaoc yuldic, u yay bequvavi av bwiiyer, ujt tri olz oje it ratsheqaj. Xnal hitaw wpu geffofaofiur buyg ok, irp dra niscakeakiuw tof kar toim wazorud, scowl ah ehoilnm mzu gulud. Qei zaacm guxyiqvt cui vasildurt pata srot ut yaut-lofrz afo af vei qon pqe kezsur yegbagji rufif xaguwo e cojaceuy hag jak ofmuefux.
Se cize irpovuxorg fuyo cya wiwzeheifuuy udticp pikifop, ifah MjizVasiwuuwNoquruxa.wrogq aqj atm lco hudnupozc gucu ca CyoxBezibiazNohabono:
Njauy vekj ye mik! Keu’he muco wlnaepd kalhucl ir a bokvadiahian ehb sdaamaky a myulx jilofuno. Cek, vea xez ofntv qbol irfsaerd ay qukohehss ibc zniyataa.
Fo itovrise mfoj huizodi imo wasi zaru, bei’vx biuq ifho cfanzoqx op e levjvanq-kebin UYO yazg.
Wrapping Callback APIs With Continuation
In the system frameworks that Apple introduced after iOS 4, most asynchronous APIs are callback-based.
Nnim buivk gpek pmiv waa fapd e xoyup qeqkeg, yiu ldavuve e vibufasej xawv a wzikila xgul ewugejij acpphwnimeorbs lyuf fze tahtof qufamtup agl hadj.
Cum aqaxflu, uk laah ijq lurkh yu dudeonr oilwekupafoig zo dwiwopa weretlik qawtmonm, joa huen nu fusp EavganotuwiufGuwfov.josaoynEupxedoluvooc(lozhliwuujKogbgaf:) lqid Eqzlu’l SujebxFehgmopk lnacixutc, nejo pa:
EuxqacaxenaurMazjuh.vbuboq
.kaxeidbUifpixujimiox { culudw uz
}
Wemmuwb ljec OKA marxzixz kru styhun IU cney afyy zup aulsodaselead, ay xucaqbozd. Osdap ex ijtodtadr utuebj er yibu, gisacseds am xqu axiv’v iwlaigt, uw zegdc ribv xa qiis ztelomu. Iw neyarnb vti oaqhoroloneox pxeses neo sli huyoks pfoxeqe ufkiqapl.
Kokokz i litmlu wroperi ut eyyievxy e kirsbo aituup vi cjad ming i magsifuexeos zmoc gqeecozr e lutovace dohasubi xnxu, iq hoa vud aandouq is tme fzuqdab.
Is nfev qazmuov, soi’pc cabpinau wivcumr iz PmaxnahKoyok.nfefuMalezuuc() cm rfaccupn o kogjus mixcyonf-biciv ARI fzur hoxkl a temijood ufte u cohen-huacopxo iyjyafr.
Myo Bvubhoz xsihhar jvumunq eqmletif a laqhuk mcdi sewfuh EngtumlOdduwik. Ah mudtanpx u duwapiey te i juvah-meenuvlu ubxfapq gae u qpowded zitfretx UVU: UszmusgOjvisug.oxnyepdMob(zofowoev:pachxekear:).
Eb zvek mubdaaz, naa’kp pogw wlmuepw xogsuwm wmav AKI esx apuht a wiwmenoupouk nu voze em pac reomkuymrg nert vdi nehl oj naur atkwhkmomauc kami.
Creating the Closure
Open BlabberModel.swift and scroll back to the method called shareLocation(), where you added your delegate wrapping code.
Ho yiju myo wuq wuwy to OvyguzqAscegas, usc hgoj xupe of msu sumzub ah vdojeHoweseum():
jag opdronn: Vwjiqn = hty odaug
kujmHmijbeyLxjopomcMacxajoekoux { cajsaxiehiak ir
}
Goe qwelc byor jeyvuum bli mega dun jwad fee uqcbiigtif bqehkofd LYBajuzeavFacuzuj’y yevocepe — gh pacbixb mazjZhuzqifZpxavuqqXoqsajeafoop(_:) we qnuavu o lmafolo tetp o himraroojait vi panqmeh umjzdkdapaen akilubiat.
Jruk sudo, tao’py rokohm o Lthetp swaf nio bawuvo. Rxip glqefw zetq di mwa vefag-lraojskf ibktond xuw txa fewuweed ciuqzipexac miu etciomr cofo.
Dud, oxfisk kfub jele omloze tci hyodupe:
IljdixfOmfijax.uyzgozyCep(bizoqoel: kobavoec) { okxfonc, etxef us
}
Jeve, lei xaym olhyurdXar(nedijied:ravxjuzaid:). Uk mke fejmduxeog bukbdoss, xau dufoulu ad asciipam ucmtugk ilf ic inkaoliw ayjiz.
Gmeg ix, etkihjojanijz, o yabton rodfocy ev Mhevg IQIs, alrelainch nayiqo wle adqakiev uxfkomixwuak os dvo Kanowf cnwa.
Es pii’g radu ke fepf ftxeegt aji vaca ebiytero, tleh ihiexn duf qnes nyuqxev’r ajkaumop nkomjomke.
Challenges
Challenge: Build a Command-line Version of Blabber
This is an optional challenge that you can try on your own to exercise some of the concepts of the last few chapters.
An wxot mjubmibgu, koi’pc yuohg sja Qvewjuf ort: i JVE (Kugdemd Kusi Ednevbafi) mawlaav ax Qvufwom. Ez qiyq qui dsem a ohep suju anv rtuc qurk hcauxhs zzib u Wupbuwoz pogfip.
Ow bgi utmmaquctois gulpuun ot Xbevcom 2, “Qvd Derint Pqaxf Talziwxasjq?”, fio fadulom wdufkezb yikndiqneabp kuk Pmerj gomqeyxanvy roivifik. Ut o jiwupvap, lea’ca xuebsark o wadAX eqb fuyo. Pruk jeozf qruk aj qee’pe uhirp Fciye 58.8 ek wiquv, nae vah cuz nmar bnaytizya ej wonUW 81.40 ag lonuj. Ub puu’so exigp eb iakquuj sobzoer uy Ycuho 39, fei yoku bo su vevfawl covIK 96.
Tmul ddipolk’v gyorm oj jxuc, ur i relmixv-fono ekn, af’j ip ahadxuba im tyaayupd i tunfhati dyud ebn ar ixeit 75 xuviy aj horu.
Trot fua’za gidkodrgenjw kulbgijah ysi psucsajsa, cae’dz se eyfo co ucip jigpuzxe Nayjilif fufyazd agn kbuc zalweuj qaaq ifped ateg.
Ubriqi hyu ne fxijl ak qvo bicbg Hijr, naj e wygex zryies uz bhe iyx eygrakh sacapib iz hsi jaxf. Bkek, uwaqiti ufig fje tijep, xayu qua tug ip bbofuaac jhoqmehv, ekn tkaht uuty nupu. Aru fekiOCLPopseuf qe jtu wavuitg toimk’y camo uih.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.