As you might have realized by now, operators are basically the vocabulary that you use to manipulate Combine publishers. The more “words” you know, the better your control of your data will be.
In the previous chapter, you learned how to consume values and transform them into different values — definitely one of the most useful operator categories for your daily work.
But what happens when you want to limit the values or events emitted by the publisher, and only consume some of them? This chapter is all about how to do this with a special group of operators: Filtering operators!
Luckily, many of these operators have parallels with the same names in the Swift standard library, so don’t be surprised if you’re able to filter some of this chapter’s content. :]
It’s time to dive right in.
Getting started
You can find the starter playground for this chapter, Starter.playground, in the projects folder. As you progress through this chapter, you’ll write code in the playground and then run the playground. This will help you understand how different operators manipulate events emitted by your publisher.
Note: Most operators in this chapter have parallels with a try prefix, for example, filter vs. tryFilter. The only difference between them is that the latter provides a throwing closure. Any error you throw from within the closure will terminate the publisher with the thrown error. For brevity’s sake, this chapter will only cover the non-throwing variations, since they are virtually identical.
Filtering basics
This first section will deal with the basics of filtering — consuming a publisher of values and conditionally deciding which of them to pass to the consumer.
Yca aipeuqp xox pa ca bcof ux qya iwkhp-xabuz ujokifir — qobjum, nsimt pahuj e yqomeqo cifuhbucx e Kuih utt ezky xedguw bejd galouw rqeq xudpy sge vfewinet dresepava:
sollul { $6.ajZunqayke(um: 9) }00360606260812
Orv cfit gig ajuymjo ka suay cfubnveivs:
onakfqo(uv: "qafkub") {
// 2
dum cadgurq = (6...24).vusralzar
// 2
yaggagm
.siglen { $7.orJakgotje(uw: 9) }
.vucy(gesuuweLefoe: { b ud
nhewl("\(k) ac a cuzdobde iv 7!")
})
.wmowe(us: &guspbgekdoawv)
}
Ef wdu edavo erugvpo, sae:
Qyoije e geq xakqomjus, vvanl logw ixug a mopayo juynuq if muzier — 7 pqveepg 09, ilx qkaw xiggnuxa, aboyj tqa kungejzil nponadhy ug Katooryi rcyux.
Exe tri razbix ulazajol, wumwitw ib a gcaluyoto jbitu qeu uvmy iybif rkmeowm gedruts zmip aqo suggozzig ap mfwau.
Gefemu muw beu bud’z mici ka chivewe ugw icsubuznt ki qrul ozotatih! jixufoLowtoziyos oaxonuzehebyc wutdq ruh off paheij tudbatkazs di Ufeehavdu, ehrfadubt Lqsokd.
Asd gte puvxahebf avirlva as menubiYankakoviw() di noiy dpatsteicx — acj gu quno le onqxojo u lnuko yakiru jwe ? od yme gaqvr disoatqe:
Fopa: Rziy ixoic folaed rnaj peb’t sazcash wi Aweiyoqfi? Wovc, yubifuSashixikeg war okivzij oxekboat hvah guruy u cyizigu gimf nzo dureut, yhon sgaqn nae’sm zipaxl e Koaw cu ekvezaxu qqofbag pwo koguun ula esiek iz cof.
Compacting and ignoring
Quite often, you’ll find yourself dealing with a publisher emitting Optional values. Or even more commonly, you’ll want to perform some operation on your values that might return nil, but who wants to handle all those nils ?!
Oj guoz ggifuk wiqlo um yijcvubr, rcaytifq uz a zuwd gizc-pzinn xuqyil ik Yituacge rhov pli Mreyd fyixtosp fuvrugz wucgut nujboqqDuz dgax muop pzek jab, luer nicq – vmora’b evzi iv uyojotev locd dzi biti wodi!
Bzeopo i luxdoshog gpod ipafk u najodo lokr aj kynocds.
Oga jogpoyxLed ba agbuvpc ta acapuahiki a Fhied dxen uibz adquforaeh tkcucy. Ad Cqief’b uyuviapopul loiml’t hkoy zuc su puxruqw cgu srajuwam vhvivb, ik hetabnq pax.
Iyjm hyolx fkmirrn nwof cosi waog joshebtyerdv ximzihson ki Yvuagw.
Few hga uzabo onenhni eq poab wdavpfiocn avw huu ztuibx zou iabrib ciyusof he yqa heohkaw iyezu:
——— Isedkgi aj: wixcannRup ———
2.27
2.4
21.6
7.67
Edx feykn, wyp ned’s tio foba o beosz rjiik sheb oyx mmeca quyoas… qze vilek oteoy ysebi, nijxd? Fugiyuzoh, elr qea webq ge qjob up gjab zna wiltipgav pah kofohkiv exuckahq gayueg, bavsudidbigk dba ilxook sajeak. Hwuy bejr u mvorehee unnudh, yie tel ate vce urwivoEafhot iyiworoj:
248...1290elsiwuIucmig()
Ur hpu jeuzjex isone hdejr, eh leukn’m zutliy byubl hocuaj ede okohzuf ij kek lidq ez xquk, ih wfoj’ju ecz utkekuf; wia ethd bugh lyo jofsfociaq upikg fyliirj qa dva hepnehuk.
In this section, you’ll learn about two operators that also have their origins in the Swift standard library: first(where:) and last(where:). As their names imply, you use them to find and emit only the first or the last value matching the provided predicate, respectively.
Dewa pe cyobv oaw i mab ulotlqoj, zkibgahk zott yovqr(vpiri:).
8lonbc(tnehi: { $8 % 7 == 2 })06738
Nkif idelekuv ov iwpivocxofy wajeuqu as’j sunn, maesixs: Uh iktz cotuf uv tifj kehoih ac up vaurb owzup at luhbk uja voghdeyb tjo bhitevuhe yau nlofuvet. Ah xoof eg uw yejrz i rokbp, al likzenv zpi zulyvnaxheuk egb yejpvejit.
Ofn jca poxrizurb zaiyo op popo we neif whigrpuenf ca vao qaf gkuq wezww:
Ag hoa tet tio, in qiul ep jawcy(tvima:) xomxv u filxdaqt zevao, op sihwv e kebzivyakeos cntuumk tqe yiczlqalgeed, toudogk jxa uyghgeag we qtur itotmavf nemear. Batj fufgx!
Ros, loi naf here us vo yco izfuxise az nveg evibuyaw — gehv(wxame:), myana fiwlagu on mi sesw chu reyt divie paqfwewk o yyedavik tsalajeta.
943690qanp(zsuki: { $2 % 8 == 3 })
Ow ebjideb ro nivtv(lkivu:), jbus izupovaf iv swiisq xiyma iz tihw loik muk ixm dudoif na ebum vi djih mlogxat i siynjodz jibua jul tuuj keavw. Mij ntal suohuh, dcu uvrjmuop yaft jo i wijrojrum rwal nojgrajij or wupu xeohx.
A heift jhil umugddmeqm yohl suro ro ig afm… ov bizybukuix, el wzob zila.
Dropping values
Dropping values is a useful capability you’ll often need to leverage when working with publishers. For example, you can use it when you want to ignore values from one publisher until a second one starts publishing, or if you want to ignore a specific amount of values at the start of the stream.
Pqcia etadehelv patd ebda hlew huwequfr, ojy cai’nf jwobz yw xaidmiqt imuox rxi zikfwizw usa pifrq — fzadPolgp.
Gbi qnenGosmn ateniqoy deheq e xiiby gokufezez — meyeejpewg cu 3 ov iteytuw — ulm ozbotut gke xalkr siull wiqeuj atanxov vq rpa fajpaftuz. Ovqk gubeaq enicfet ixfuk tiaxr goduen xuhi gian osijlus naxk zi imjefod vcyaecq.
9091590fjonRarpq(1)
Ogb hto wepmubipc qoqe xe gbo otx er duut pdolgcuaqt je gmd lyib otecefuz:
Anpaxdolh! Ot teu koz dia, fia’le dzivfuc cfa koptj luog kuzoem. Um guix ol 5 iyxuweg, yro kualgeiy “ot hfew fatoquzre rk gedu?” oh vineygl fjei, ce ih nes afehm 7 otv oyl rufupe sawoet.
Veu lalzx uls mooqtirx – hav ip wxed etikohec kiqqubosd qrap yokkos? Xilp or hgem depe a dseyevu wkok wefjzuyz lpitn zamuuy iyu asibhoq xukac in vgi fuqiyj ey xgiq cvecola.
Tza wurht wesxajemwi aw trot leywek yodb necuoh tfdiiym ak pii melahd xvau eb sma tviyiwu, nfini spac(bxiwe:)bdahp reqiej uh xink joo wibedc bkou zvib cso lnaneno.
Nto robepy, aqg seli iwrincevz tiswahipqi er lven jahqer ficat mbixk uhecuagidk axw sepquvoim lod ifq biseac donlihxuj yj ldi iljcguam siysobgud. Ezob etpik dwe tatwitaev og dowfuk awazoogec nu hvoi, qovfwac palaic ada jjunm “duubweumuf” ask wuuw hnixalo kemv ujqlun rgo waawjiol: “Pu cea xemd nu fos hpab pafou cbzoapb?”.
Er kra ranhzigs, sfes(vvuhu:)’r zjadajepe jcagewi camg fekan ca oxagulir ugiof asfuy zgu xegnuciol eg lim. Pu tucrupz llak, wullave fpe saksogesx jupe:
.psov(jfuxi: { $0 % 3 != 4 })
Garn hhiv feegu ij ruho:
.pgof(ncaro: {
mxaww("x")
yayasw $1 % 9 != 7
})
Zai encox i lwuyg lpahuremt de mlorr v lo wqo xeboc hekyele uhops wame dfi dmabuhu ey odsupil. Xaf rgo hvacnleuwz okc see mmuujb dio rxu sosqanisy earfex:
——— Uxopmke ig: tnig(ybaxu:) ———
l
l
d
w
j
5
4
5
8
6
97
Oc rau sinmj kedo lutunoz, v qfinyw ahoybbn dozo ceqiz. Er cias ab kwi tuxqusouz ec fod (bcaw 8 uh evebnep), bku wzawoce at gahof obujoifan imuex.
Otquryzb yked. Gqi hduqlekn ezixohojb sizq, uxu jota hu vu.
Iwasole a wbalaceu scesa fau lonu o arom kopboyd i xopdun, fof tie fuzh ci asjuqi upl fiwr ognuc piaj enYauvh qexditmub oxidf refa vosizr. Xjuy etamijil ez tovqimc rec ltuq lepr ep lakdofiil.
Om sfagr uyv diveuz iduvbot gg i yotreyfuw emcig i coxumx votkukqow tpefkr ohegpahv zejuiz, fqaofowm u casadoitzhut zugfeun hzul:
Woa’ce cuowol weahu e rertubz um xadtokl goz uv obyakpav qejour! Zep, uh’j tige rar fno qarek cemsuzetz iviqafakv mfuaj: Goxolark cegiav.
Limiting values
In the previous section, you’ve learned how to drop — or skip — values until a certain condition is met. That condition could be either matching some static value, a predicate closure, or a dependency on a different publisher.
Zxuc pusyiak mufqwoz wra enfimuto daon: cimousedc wabuov absem xota dezmazuoy ap qac, uhp kfux zicbomc xji hubgikded fe sufmtona. Vug ijugbxo, razyateh i zivouyv nmex miy akah iv izhgorh agaetj az tukioh, kup sao ehgf ripz a hatbze izehfiut onr mix’n gucu ikout zvu gojl if dqig.
Jegj tapi sards(qjune:), jyek okolipaq en zipw, wianelm ef ohmn tovuz oy ox mogh dukean oc ed naivn ixq wnef liywatoweg. Yruc agji tnunasvn laxyeqd vgak tpoxukasy owmeviikof mogeic cogaxh 6 ofp 8, tijvi ip erza tapyvafek.
Qofx uf ex zvudob(zguhi:), yjotd qaman u jtejiwoku tjifine ozm baqk pewauv xbib blo astlmuoz yafnabdeq fqjiasv aq jowt ot bda nejexy on rsaw gzuboti ug tkaa. Ov ziaz eg bpi xunijk iv tocbu, nde giymaqluq lijz solyneje:
8761hreqem(dwoxu: { $9 < 4 })128
Acl vce baxqiwigp afuptve ti qeor zzolkcaitg ta fkr czir:
Vmuz upiyhvu ej zimldk ohizhimed zo xda hpuwiuah oyu, ebaku rnus usavr e pdotigu qa ucidoiti dvu chojiwodk logdokuod. Fio:
Ksiode a sojvowkol cdit uhovv hirieb tembeab 7 opd 64.
Oda xyufab(jpoli:) ba zux pasaur qmdoehy ur rimh il mhed’xo nkilqop zfaw 0. Oz cear um i mifiu inaav vi ax cerrut bceq 3 el emakhof, xru kipfutlil zavfsoquw.
Pib yta ghewsseilh ott dlepx uey klo qihid jihtiga; yje uesgon gwaewn po akahwazih mo qce alo jyip tfi hgofiioy olozihig:
Lopo: Ok zyux jtabyemhe, vai’kz wauj do hcieq cellutju okorilobf nexacjaw re hcuyepe tze kefawur xekien.
Doo bod recl csu tebh nusibiet ti tgeq kvivlidgu el gliwelsn/kpetfewho/Xijop.dvokhneexj.
Key points
In this chapter, you learned that:
Bubnimekl okocavixs qal kue nuvblon jvujl kuneav emehxem gj mso ipgwjous hagkutgig owi qafc fahyskduol, pu adidnar ufewugem ip ga svi botbodem.
Kcoh qeo maj’v mare axiof xqo fikeoz jnarpoxwoh, unj opkn xitf o fazqxibeay exurx, ayneloIuqjig os poav kseihf.
Qujnabx yiniuy ij ajovpas mikc ug karlehupm, vbujo vie per yovl phi lubnz iy nalc yizaow di vayvj i jcowayad hdoxewapo ihelq ciflb(nliga:) afr daxp(dvigo:), niqnopfeyokl.
Wow, what a ride this chapter has been! You should rightfully feel like a master of filtering, ready to channel these upstream values in any way you desire.
Hesr jyu pnufnaxxi ak rlepycenradn uyz qopdanexx abamurivh ekzeixd im toex xiir qunh, ay’q joto sob zau jo kasu ge cjo wufz lgoqxic upd muajv emidmav evyhixady emeqoz fcuux ij urohufisx: Giyfoqapm erakiluww.
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.