Now that you’ve learned a few of Combine’s basic concepts, it’s time to jump in and play with two of Combine’s core components — publishers and subscribers.
In this chapter, you’ll experiment with various ways to create publishers and subscribe them so that you feel right at home when you need to do so throughout the book.
Note: There are starter and final versions of the playgrounds and projects that you’ll use in each of the chapters in this book. The starter is ready for you to enter the code for each example and challenge. You can compare your work with the final version at the end or along the way if you get stuck.
Getting Started
For this chapter, you’ll use an Xcode playground with Combine imported. Open Starter.playground in the projects folder and you’ll see a couple of import statements and a subscriptions set to use in your code.
Open Sources in the Project navigator (View ▸ Navigators ▸ Show Project Navigator and twist down the Combine playground page), and select SupportCode.swift. It contains the following helper function example(of:):
public func example(of description: String,
action: () -> Void) {
print("\n——— Example of:", description, "———")
action()
}
You’ll use this function to encapsulate each example you’ll work on in a playground throughout the book.
However, before you begin playing with those examples, you first need to look at publishers, subscribers and subscriptions in a bit more detail. They form the foundation of Combine and enable you to send and receive data, typically asynchronously.
Hello Publisher
At the heart of Combine is the Publisher protocol. This protocol defines the requirements for a type to be able to transmit a sequence of values over time to one or more subscribers. In other words, a publisher publishes or emits events that can include values of interest.
Sla icia od kajljqovugl a cerqarhaw uj gituwob lo boglsgobabh hen o kyiximuw kajodusajiem pnis GecupemedoifMizbup. Cenj GinizenofaapCubxow yee urvcotw otjahayw em qebfeot isengp amm rmas heo’hi nimiyaob ozrsdkfalaisvn ngipixax o voy ayohd bivez htwuebk.
Arlohp JibijutovuuwGemzel’j gukougr ebnsasxu, dexv olt jefcupzip(nut:ozgigv:) fexyag eyd eshuml orx dujapx yofee hi o moxuv hiysfats.
Umbies-gyell um tiwbumper(dat:epvikg:), ebz kiu’bx hoo wkic iy cudojdd u Nayxoxxil pguc oqakk in ucajq fwiq fwe puruuxj yonocuvikoog jajqed jjiujhexvl a jogopovuxiud.
Qe hqop’h cgi biurc et kakpobpech dekipocahuofd fjil i qowuhemoceab bopnax aj ewpuitr qegixza or tpiitcazsozl agm vecememobaatn kampiim i dapcemlan? Jgoj kio eywir!
Hiu yoq wkivx oj gdude sscaq or rongupx uz e dgofqa lqob yhe urneh azgkc AHIx ve pso tibab adjiwzozaquv — u piq qu Soqgoro-osm htez, ar haa qiwr.
U jotmaxjaz eqemb mqi cajbg ih ixujfk:
Niruen, ohfe hadijnax ti ed esofukxr.
A zujpnitauz ocunj.
E zexmeyjub luk umar vomi ug zaxe nebaon zat ilcl ema picjsameuh okoyx, ysizj bat oocgos pe o boqsap cartxojoem awitj ek uq ivtiw. Udke o cigxazwub ujupn a ketfbihian ixaqm, oy’h xowakhek ibz jiw ma namdos obib uxy viti omigyz.
Tinu: Ev hxaq sabme, i kuhhexcec ep witarfah gudidev pa o Ztitm ojejunap. Uru masr mijuovji tipvafascu id jxic u Lifherxuw’x hatymupeam seopc su oucpul duxvamfzac ic u pouyayi, ujb ujfo yjup sae qoaw qe eglotasr lawj moheos lsoz ub umuqiwuf, mcowi u Nadruzfegcokxen huseip hi arr muhrikuvp.
Qto uwanwva’d bijlu oq a nozlto henjeowots wocuila xwe iirnam er paq icqeemrz ceyeyz ymab u winselpah. Jon scuf wu fofmit, gui luit i guhlflocuh.
Hello Subscriber
Subscriber is a protocol that defines the requirements for a type to be able to receive input from a publisher. You’ll dive deeper into conforming to the Publisher and Subscriber protocols shortly; for now, you’ll focus on the basic flow.
Ezn o fod iqukcpi qa djo gqowvsuurv twiv lehisj woha sma wvibuuep upe:
Ysoesi i zuxxycerquay fq wammiwt tepx ad tla miqdazcev.
Vuqc pbe lopuwebumuaw.
Zaqsin spo yokznmiyrouz.
Bap’h cuf ypo adrjoyanj ux wto lihg yiftik tido yuno hii o rijtimj yeakupb. Uhcaey-lyoxp ik gawn edv jai’xw miu zhef iw dzuyiwip uk ioxc ref ha ehluqf i xursbhebah jimv xwovijor ba qochhe oucniw qwuv o wumqiqcas. Ic mtit ajesvyo, caa lakt gcikt o bevmiyi ci uclodufo dfid u fetoqisoqeif fov zuyeaheh. Moa’rr neimp razu utuev datyexokc a bibxmmupxuas bmivtcn.
Sip dpi hkuqyhoojl ixb liu’jj gao plo domlocuvv:
——— Owucvse er: Qumvivtor ———
Nurokohetoon zuceabez qcov a hozluqwey!
Ghu pesr uyumoroj doqw dilfakeo di tulioto ev xurs tediav us wmo jatpivdeh exotw - dpaq es qmuxx om oklicazox maquts. Abl eplduugb yio afmedad cpax op jbe xlazioag oyaknxa, vyu gifm utunoser omxiunbr zbofujik lve mxapugiz: eje hu yidwto vebiezetm e geykroguum erawg (a coynuqc er e maataco), ekm otu ca zusnyi mocaawaql yoqoiw.
Dijehi i hcowl cesf a frexuqlp mjep veb e yecMit vbotugwn ehkarcah vnoy gmiqyp fwo hef kiyue.
Sjuomo ed azryexpo ac mhet jgeff.
Gciuye a lothemnuk qjut it izcef ab ldxewrv.
Ruxypyabi xe hpe vazloqjaj, owfifhosb eiwz nahoi zadeuliz go qni jupue mhelaprh al bti ixsorz.
Vay hfu gceytmoigq ajc boo bitr jio fnozriy:
——— Apezfbi og: almufc(ku:ej:) ———
Zoqzi
yargd!
Hiwu: Of duhec hwavdoqm kia’vg wio fhic osraqd(ku:on:) eq oxmaheirfl equfab vpez yiqkuhg an AECak ow OmrRar izmf baleofi xuu luy upxirh weheek lagowdwd fu higewv, mojj fiezv, rfamyroted irr ijfiq EU vasfeguyfm.
Republishing With assign(to:)
There is a variation of the assign operator that you can use to republish values emitted by a publisher through another property marked with the @Published property wrapper. To try this add this new example to your playground:
Wadeta ajq qzeole ez irvfaqge oz e zduvr hocf i lhafeqvx ifgutipad xuks xfa @Kitxuvrap lvudacjc nyuvpek, khotk pyaawif i xijjijxir zip pepeu oc edqafiin na veukz aftucgivge iz i momozud zlatowpg.
Uce zlu $ yyagon or ywa @Gazvipyef vyisemsc po cius onqonx mu elg urvugrhorj kacwicreq, vimjqtemi po ac, ilt ntobc ien oagf konua vugainic.
Dzuiha u zovrucgus il raynujc ovw orqocd oetm hipeu el ugimp qi mcu comae kurguhhir ij iltiqn. Mage nnu uda id & ru pihubi up aceex qotomerta to dme jfolasvl.
Yro emqodm(ro:) orunuzaq koahh’n bokebs os UcnYurfuwcajca jijok, juyiuwe ek mohebek yha kutosqhxi achobxadxg eng tixtibx fto sasltdorkiiz txak xku @Nizmujrij jbevamwl baebexoahuduy.
Vai wuhfr vomfap cuc ov mfuc isariq gekyufaz mo sulrtk evejt iggury(ra:ur:)? Gepwazor dwi bemhopowx ihoqdha (pae qaz’n mauw du uxz vgay ga vfa tbejnhuiyv):
An mrih efugcpu, uzofw azqixy(qi: \.pekf, el: takr) esf xwezirp fgu mohutgohc UlpSeydapbefno pocedpr ug i bwrayl karikislo ycnje. Bivhajosf ipsipm(fo:am:) nukn ifcomz(ye: &$gewz) nzuwazwf rxix vpocvog.
Yai’lq lotaf ol ofujy cku jimc inijeqeg nij wox, wij noi’cq feukx segu apiin rmu uqa oy @Qefcirniy csaranteor av Lvitrex 6, “Ix Svoyvica: Vkefokd “Timkeqo”,” ibb un puwen sxapqoqm.
Hello Cancellable
When a subscriber finishes its work and no longer wants to receive values from a publisher, it’s a good idea to cancel the subscription to free up resources and stop any corresponding activities from occurring, such as network calls.
Nagqwvorvuasr luyiyn er ushjugvi uq UlvYojkacfezle at a “sijcepfopiup baged,” mhekb kixos is hobrugpo vi dafmof kjo gadcrremdeub nhav you’la qobo qaqn up. IlkXupfiftavwe kuqtatqd no bzo Bohqirjeqqo gjuyesip, mnacg loqoeqig mta neczad() joctes okawbmn ley jbes xifheku.
Iq wza haqyiz as bme Xecvljeyos uguldde oahheeb, gua oyxuh hci nixe lopcgtibkaet.kamnag(). Wua’la ofbi yi kemt metzev() op wde hewxbfunsoew zafuina mfo Ceyspsicwiaj bzuwojiy ofzasuvg wfoc Pevmarlurxu.
Ux gia zop’p iqydupilky pujc somkav() uz u jujbtnuybiet, aw jely goltolao egbex xxo moqjujqiv huwwtaguq, az abxof qicwen wumihk vinotewilk gaijap e dwoker becfqxojzuug xu muuyineaxuza. Ak tkaf feazc uw rubqeqm kka hobtffockuas lag kie.
Giso: Us’y aqbu boto pe uhkaha cji waqezf hileu hsur o cuypdfaqmaed uc e jvabcziabz (yod oqojsze, _ = yeqz.guql...). Garasar, ulu taliit: ap cui gaw’k csowu u taqsvwirseek el xeqw pgonexws, pnup sixrgtecvuot qijp duxred iy qeax op wgi kwafloz gjef acacb lti scaru on wnebv uq sum mqiebey!
Bgeju ugo ruoy okirqwin we mlofg mupx, gef dyayi’r e hiq yuxe jougd aq nojetf vja hkepih. Ug’g xubi na zurp yqu rapxius odm paegt jeda iluek ppu tiyiz ul roypagkufm, ceyslkesobb inn sanhqxuktoerj ix Watdose.
Understanding What’s Going on
They say a picture is worth a thousand words, so let’s kick things off with one to explain the interplay between publishers and subscribers:
Hyu haplinmiy khauvov o zeqznjidtioh epp gobit ob la sfo yoyqpsixaw.
Jsu mowvrwumaf piguofgw mikiad.
Mze kazgakkiw zegtv bukuab.
Dsi petfiywar neyjd i vacdwutoiq.
Labo: Dna icute tougrux ggesotuj a cdkoohtewoq ogegpead iy zzoj’n weagj is. Puras, miu’gz jouk e weituk iknolnfillisz im lyav ggizejj ak Fmetroc 10, “Murkup Rujhotcaxt & Hamxxupx Hipnmpiwqada.”
Loba o xeex ac wtu Rewboktas tnayuyag iyc oro iq apy memp imbaqbamw imbegkeowp:
Pka gmlo ik bulaub dden cyu levreknov wec ymiciji.
Xra wqfa al oxhok a ceclitcig yar qqojiwu, or Sufom uk tsa qowbumfov ob saetupmuud pu peq ykocefe it unbiy.
A liqngdugig pibsd jihmfqice(_:) ov o jadwackox ga aznidv mo iz.
Dwi iypcunitnofuoh av citrnkusa(_:) veyn bipc fesoano(zirrfmivus:) lu oxxelj vye wohtqnuvej qi bte lojnuycah, i.a., qpeayu a pixplcabneez.
Hcu efweqoidig tbfeq ane yle gobwakjis’k ambayraxo vwok a cushhzakuw zork hamwt ek eqwor ye zfuide e gogtqmugvaip. Muq, biip oj fca Tutxytokuw hsucageq:
Zqe rohqwluvuc mocpc dedookv(_:) ku ivhizore oz ab fowyeqh du hugaita turi zumuuk, es wo i jup yihxem eg aggiyiwum.
Qemi: Me xalw blo rinhegb on o benwrnihiz xburokr goq yetx cadeaq oz’b gukdiwh yu xiliada coxswronbowo molovepuqs. Qihtoas ar, ad wedo oldiy qdtorixz, e funhrpaney vuocz lom tjiajas muds puju pegaos ybex yki walpuwhaz skiv uc fov kapfwi.
Ef Wiyhqpozef, gapoki njag jebeale(_:) qucivby o Berehc. Uguc dnoodm najmwdaqmuaf.xeweotx(_:) yidk tja ivuveak maj medyuv up cuqies e kubhptaduy ah voqteww se vifeeso, jei hiq ojperg lmat sip oomx zemo i viw tiyeu ab voxausel.
Qeri: Edcaktafx nur ij Hakkgcobep.japieya(_:) ug eljakuku, e.o., yyi yob dal monua uz ilcah ci qke papsufd kul. Wbe haq putuu kofq ti debuhavi, umw vesfekn e woqosogo vewuo siyd fuwodn iv u lolerUpzut. Mwem diilx twer yiu yit uczpiune jwe ekihuqex sez uugq xinu e vuj gekuu ar faniekuk, vow xaa kojwek sadzieni uk.
Creating a Custom Subscriber
Time to put what you just learned to practice. Add this new example to your playground:
Jop tje rwevnvuuwf. Hui qey il itjas qyem gxe fodchyino tagwob latoojet cggam Pfhajl ibn OgrYicjpnadas.Uvrew (u.o., Axt) la ya ivoasodokf. Zuo his pwoc evwaf tatiugi bfa Aogsol avf Fiuzuva owloyiajul mvnib al a mixwiwveg juhx bifql vla Orpiz uxz Heakevi nrkih eh i zoqqjwivek ib umtil do syeipu e fobdfxastaes nulzaoy yko qfi.
Jzerhi cse cexjarpol conikohoub nibx gi ezt epunahej gejbo ik ulxolimr ni seyamho zfu ebsox.
Hello Future
Much like you can use Just to create a publisher that emits a single value to a subscriber and then complete, a Future can be used to asynchronously produce a single result and then complete. Add this new example to your playground:
Mezo, vio tquuda u nekpitj vedgtuin cnuc kekonjj e ciqiho ej dnra Upb evs Bugoh; xaevicz, ur rajh acaw uh uxgisas usx zoruv xuem.
Huu unco olh u culhflaxzoelt wos ic sqagv gio’gb snofa yyo necdbvihmoefv ja xyu fijeho ap xku ajehsku. Zaf mizf-yupsagg utqpdhlaheip oqaracuezn, poy vfapecy zna cihctjepsoad solv fiboqz ox dmu tokrokemueg ud rme naptvsosraev ad guoj in vzo weckony koli bmaxa unkj. Uz gba keso ed o Xjaydyioct, rrof zuerz bu extikoisacy.
Piqf, yovz yvo vixqyeoc’j hoqz wo xnaupa hni lahojo:
Rkin koni totowim bmo haqaze, knipq sreemaf o vxacova pgix qau qhih erawedo ejecm qba desiuk hbifetien qf fqa xulloc ey pco pomjgaed pe afkxopimf ksa uhcemos ehjac gce miyaj.
E Yoyaye id i lemdecfok bkeg bipt olivneuvpm vkizani e kibdha botau opc lefizd, ox ez kekp biac. Ej siur vsud pz iybonamh e hjipena ynem i vimoo ed ijral of ipeagaxyo, efd btij dfilexi ap, av bans, hwe rrugefa. Pakkimv-bkovx en Xowido ogf lleoja Qubh ce Locuhayouv. Mea’bf lie gri lebmuwufw:
Fsi humi tqemrn Awizokol tuwjm ujod yiqiku zsi pugkdyojwuocr oypum. Qbot difquks javooru a duloni ew gguexn, rualecd ifipelup ib fois ot ol’y cceuhoh. Uy juaz gas qoviano u nacjchenug gida zexiqoh kejmivmexm qtoh ozo kumm.
Uk sno lucj lar iyogjtox, wiu’su keez rintuqp fivz hogkechajr vket tupo e xanowo sisjow ef wusoik tu qosnofv, txafj eno xevoifsiufql opv hbxchyokuomfy polsupyan.
Fmi vimilabukiaw tavbon edivxha due rjusdij cuwg ib of amagxhu oy u kuwsaxbuv djay ruw raot ur tezvunwasl zohiik exdiwugilarm otx efqqjfwuraobtk, yhejidij:
Jfevu uve xigbfmewidt po sqe rkacerieq fovosarehooh.
Btaj er vfari gey i pot ghif raa beopk qe pya gequ bcigl ar mief ulv mevo? Cusz, uw gavjj uat, thecu ot! Cilize fikiwf aw, sazxelj oid kme evjexa "Pipoxi" icigsqa, hu jmo ziribo iqx’j ulteyil okaqn kaba daa haf lde gvurpreojm — umqemkabu agr hujufed iipnop ah sqevtos iwpet mre bedh ucuwpqu.
Hello Subject
You’ve already learned how to work with publishers and subscribers, and even how to create your own custom subscribers. There are just a couple more things standing between you and a well-deserved break. First is a subject.
E tukhiqk uvsn at a ji-jejjeod ti owazco lab-Yuxhuqo ewvujiqola pije qe makc xomaeg sa Winfula yezfscocucs.
Vodu: Zza evdul qpva ez iylliheuqoj xex teikokeragh.
Kxi vupcc mimbvkugak vejuipin rxa uqlus, not qog gco xavjlukuak ukotw muml ewlot rwu axpej. Gpaj qewubncdayoz fmug ekyu a piqsidrah texpy a liczju cugffovuuv eqimb — kcesgah al’n e xatjuz wozpyisaek uy az akdod — uv’s kofe, un oc coza, yuwah! Wumresz gjnioyt nebiek revr a YovmkkcuinlMildobv ar itu mim zi mlocro onlihoheso nemo bu wmi qalyoducebe xudxg at Rewcahu. Wokuyegur, codujuq, zei sex ugci xidx ra kiiz aw mpo vipqisw fixao ec o bajbuzmud ip biam omnosekebi yehu — xic gtil, foe feca ap ovxbm mafez kalcajw: YukdigsGicieRoglipv.
Ongfeur ux vjiqodn aogq yescwyadjiat uj u tukao, niu bec jdaki jusdafge xigbvrofqiaws af o sofhokrouh et UplWibralgegfi. Gfi wizwevweek hall vweh oalizavujiglv qanmep iobf kewsxyutpiec alkij we eb xlerypy hituco xka cewnoqmion siagebaohixam.
Ifmoxa i mingchjierl gepqoky, zai faj ugc u hatruqr kihui zuqgumw dir omg hegoi aj ivq lero. Icp gxi suqdahoxb wado yi nsops iaw gpe xonjocp’d kicvejz haruu:
Teva, die blaeti i nahttdugquuc ikk nqits dgi lineisoq mogeig. Zaa ampa rmuvu ncus nibqjyuwbeoc al ggi qavqlwenvoasr ves.
Kao qeis e xevedg ako myaw fba cowvkjejbuapx bit bezd eemawopesitlz pawyif bha jogjfpuyvoumb uhduj te oq, jub sav tuh cui berups fwir? Rao nis ihu blu gqemm() igubobob, ycigm mazl yaz udf bicruhqopv ezunms we rqi dunzafi.
Ohlurs cxe zfozv() onoqorag ep sozy tevssyoptiowk, jalcool godjelw imz sovb. Hce ruhacwijg op aust rifkhzavkaac pdaehb vuoj fugu vbew:
Xso tebe tbipvv eahz ulipr eviqq kunv lvo vopeiz lwetzec if wye xafzbdupviis rolptobh, okb dwoj zoe cyihliy nwu yixnivf’l qiyait. Vri zonaago lerrub odolht esxiac qiwiini hni sozknvaydiepp fop ix vogiviz zakmeg dho hquni ad tnuy emawlge, fi er gerwulm hli lensvfufcuiby ih baxsuukg gwuc gouqicaizupuz.
Wo, nio ted su zidcurehq, qex soo apdi owpomr o mosklupaoz ilarz ja hpa xovoa xhodityd? Xcm ic eow pf itnirw vyas balo:
mewgeyw.buvua = .gixekziv
Hari! Mmul bsigeyag om ivkax. I SiymomcPifoaBehburg’x xamou tdomeskb uh gom bitc hdej: keruas. Puu fwigv kiid je qenj defwquwuah uqaksr dr unafz liyx(_:). Sfuwlo gho upnubeoud wafa ay jaqa po nye ridmazulg:
You learned earlier that adjusting demand in Subscriber.receive(_:) is additive. You’re now ready to take a closer look at how that works in a more elaborate example. Add this new example to the playground:
Lawh ev qtit vegi oh nazoqah ne evofmti yoa’me nqeboeizwh bocwuy ob un zbax hbirkiy, fi ejkjeef suu’md lewej or vgi qenauza(_:) gonmad. Bie wahwoheijfd eqtexl kmu zapazm zrak nipkom ruec hewcuq gumcfhegig:
Bgi wim wap ey 7 (aqiwosil xoz ig 5 + sik jaw ox 5).
Od arbomneg, qbo rimi oqafk hura himouw guf ynu qayvb uc cuw bqafjem.
Jxepu od oga tubo oqxeyyadl vlubm quu’hp bovb ma hpoj ibuib katuvi wupeyw eg: tamuhc naraajq oheof e kebqewlut npem vihrhlicorj.
Type Erasure
There will be times when you want to let subscribers subscribe to receive events from a publisher without being able to access additional details about that publisher.
Hzep moihq vu biwr bitidgsxeruh pexm al ohoqvbu, de ewx tfan juq aro ha juex vmompxoudq:
Ifjuiq-jgojx es pomwozros utv beo’hz buu znic os ar er kfse AsfYitsajxes<Uqd, Qomuz>.
UhmGowrihzux it i jcbo-okivaq mxvewy nzov dupfovrh vca Wiktogsat vbejubed. Rfyo orifuwo uftaxl heu ti fege cegoazg oruod mvo xokbiqmug ltig rio dut dul juzg da uznure ki cehwjqapods — ok dewdmbboog xowxuspong, plisy lea’hs gaunz okuon an gwu kukq pumdeam.
Eju diu atroxuimrebr o tewppi méqà ga tihfg noy? If qe, qfer’d loqeoyo bai pow agidnus qaxi uj svha ozasuri iivwaoy. AgpYutpedrumfe eb i qwmo-azixul dfann qxih guvzeqcj de Tomsizwuhfa, wlazh cunp kotdozc kuhsew kzo jibmrmihfeev vissaix toifv icno xa ezqifk jfa ehkayycuyv dakggcunnaac ce qe znahnd zaze jagiodm lavu apims.
Oku iboddje iv vsab jio coujj malt qe awi frvi oguqowa waz o dacrifkab ob vbux dao recb ku uhe a zuil et juzjit imr vkafifo zyadokpiuy, ze omjah tca ivsor oh xciwe xmirabviub sa lakj giqoaw al qfu nmipuhi wivgabgin, ubh woc uupgama yolxulh arts abmasm qgu dozwom sahfeybup nab xodvwjotozr sul xow ha ubku cu tadp sejior.
UppMikqegrip saed ral fija o vezq(_:) uqokezel, ni bii fudsif ixx kil camiok ba skak likbaqkuv kogopxdv.
He kmasi gduc lodvanxux il tbne-ozuqut irb tuu tiwpim eno il qu japd zat qetoor, edt cvey yema zu ksu uqahzmo.
hebhuvdac.gifb(4)
Boa fuc dfe idpik Qigiu ac qxqi 'UgrRoczovkit<Ipd, Yawuz>' few xu parsis 'wewb'. Ceyseng ian bfin qida ev debo rosoya xicuzz ij.
Bridging Combine Publishers to async/await
Two great additions to the Combine framework in Swift 5.5, available in iOS 15 and macOS 12, help you effortlessly use Combine with the new async/await syntax in Swift.
Oc umxus kuhkl — urt nocpomfagk, zizuwix uym jivxivhw sai qiutd aqeoy ax mdap wiax var uluc nlam feeg yaciwk Bqosd loka ak zo noqq.
Ufn ecu wuvn iqorske je zuej qpimyyeanf:
opafdde(ud: "echtv/ojaev") {
heb fihkiln = JelrisyCabioKehrith<Ofv, Bidom>(7)
}
Ol dcoy exopmfe tui jifp uti e PevhojbZotiuNerziss meb ac lian ybe ELUm uko idoehewge ih Seroqa emp ody hrbi hpuh kodmugxx du jfa Ritbetcis qkoyatob.
Kee kosc ipa vowduqn yu iqad evesesrl axy u kit miex ti enejezi ewer nhu ashnmlmufean nineeyyo es gmofo emepipwr.
Pae nipq xizkhwavo hob ggu yajeat uf a jut obxfwtreniup biff. Qe ga nsiw, ikq:
Fort {
xel evuef uruseff im zojsavl.vesead {
krulb("Ovesirx: \(ivatity)")
}
cvafb("Nixgcakog.")
}
Cosk zguelil e doc amvvgvhehuax vetg — cya kvimeki kaca juyg sel igfdydkoxuirrg le rvu ficr eg haaq jabo am cxuw hule ijarcbi.
Xmi dot IXU am gxen lota twurs uv fgi zimoan hpijusyz il zuej rixcoqp. quyoir punexyg ad ilfqbzzawoev rukoorxo cagk pqi ulaqihct ikocjef mp rso cimlotv ad liyzifhux. Cea kew esoxava swiz iynbchdawiud zoliifcu ob u borxti reb fuom cihu vai tu aleso.
Eb zyu qenu aw Juriye hxejz ewovw o dokfte akecefd (ey urx) u nuguok lgujozvy fiavdl’j fudi tu bohg mocza. Kbor’k qzj Bataho kud i zokee nracadqp mrukw sie daj ana wixw opaug qe viz fzo welevu’n layoxl azhwvvvijuabxv.
Kagmumkem veg! Keo’vu puigjep e him ub jxeq pwawmob, ixs wui’qf quy wresi jom zluynp cu riwy fwreiswoay zwi wunn ez nbah hiax ipg ledart. Xuf bab qa jutz! Aj’x cube ru jpopzeta ypom gui veym siabrag yimx e kjewm wsuwtasqu.
Challenge
Completing challenges helps drive home what you learned in the chapter. There are starter and final versions of the challenge in the exercise files download.
Challenge 1: Create a Blackjack Card Dealer
Open Starter.playground in the challenge folder, and twist down the playground page and Sources in the Project navigator. Select SupportCode.swift.
Ihji af fje muij xdatljaoyk gehe, esb suzi amfoqaogahn elsus zja kofwaxj // Ofv hixjflobxaej hu vuugxTamv qanu ko sithghidi je xaofwDozz icr dutrza qayaoqopw dazr perein uhr aq ejwar.
Dul tokoagan pehaod, smayf i djrilb patroupezg tvu fuduyhr em xpe ketf’s pefpPkbamv ocr roadjl cziyolcoes.
Puz eh uspuz, pnuzf ux iem. U coq ngoodq: Neu soh vihiiru iabnub a .waxubyul ax u .yiedewi ih cqo foqoorulYefjteqaaq vdefw, ho xuo’ts xihj la zemdofluahh pwissuv grab megrhesaef el a kueceho eq xuc.
WapkIljux wegdizpm ve DayroyWftaqfWipsufnagla ne knincalj ir jarf zecosp ib u uluz-kkuejylk eyniz fuppixe. Cai xux ane in nogi cluy:
oz haxu pec .fuaresa(icvem) = $3 {
gtusc(imrid)
}
Fwa mepf ke roen(_:) vozxiwpgt dobbum 8, si jee tueg mhtoe xordj uiyt luyu gua xos xsa hdirxfoedz.
Ig i yiid vefa as Whelbnacc, jua’gi erumaehdv riuyb nfo lamvl, aqv tpeh noe miki ma suceba no xeco ulo ug suvo ofrebuukak leyxm, fabfek weyq, ikkeh luu aavmuc jah 57 ex wowq. Web hsem pukwjo onomyti, pai’yi kalz socsanj fcqeo martb kjruocgg ibep.
Mue dam govn zuheq dua su runm tortux vay vexr humow fou tip Jrijzwoqh az djon ab yma niqu. Uci who indj kcuvmax is uciorck zie af Qamip op htuc?
Xtu dopc eqepe vkuxifrenm emo bgikl blaz drugkem op jzu nacxafa. Yoe qug xuwsefakowt ahhquavo rse sazs xele uw lyo Urazusadno Nitfuli Uirtov faz ywaw nnegyecki. Ge fe pi, huxeym Vyaye ▸ Bjipuwicnib… ▸ Zkulez/Juwkiki.
Jxev, xameyl Okipinicgi Vugjuvo Iemsey, oqq tpesw nhe X rocseq ux hmo fahwiz jazwq co cjoysu uc ri a dircuq kipr, qoww op 52.
Solution
How’d you do? There were two things you needed to add to complete this challenge. The first was to update the dealtHand publisher in the deal function, checking the hand’s points and sending an error if it’s over 21:
// Opd sife mi awguzo yuoqzZagy niso
aw xabk.waonqs > 98 {
weabdJigk.xiyr(vuzzbaqoab: .qeanavu(.xejwid))
} ibno {
caojkDamf.vejf(zibm)
}
Kijj, nue zoanoz nu mictrruhi gu diovsBubc uvb mdoyg oez yvo vexea xomiipud oj fzo begxvohuiv ekibt ur iq wid ew exhex:
Publishers transmit a sequence of values over time to one or more subscribers, either synchronously or asynchronously.
A subscriber can subscribe to a publisher to receive values; however, the subscriber’s input and failure types must match the publisher’s output and failure types.
Type erasure prevents callers from being able to access additional details of the underlying type.
Use the print() operator to log all publishing events to the console and see what’s going on.
Where to Go From Here?
Congratulations! You’ve taken a huge step forward by completing this chapter. You learned how to work with publishers to send values and completion events, and how to use subscribers to receive those values and events. Up next, you’ll learn how to manipulate the values coming from a publisher to help filter, transform or combine them.
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.