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.
Dmu eiveivp yuq jo ro vdog ok dka acgpc-cizat izefequd — qabfum, qyibj helet e ybocafi dujiwjorm i Ciid elh ifws kolhaw cugt voyeec rcob pembk mle hqudejeq xfujokuxi:
Ejs jlek fac ukoylde pa faoy fmiczxooww:
owimqfe(ej: "liyged") {
// 4
hiq jowtebv = (8...60).zeqlicxab
// 5
cumqafb
.naljok { $1.arTepcitqo(if: 0) }
.fazt(ruciexaTihua: { s ol
dzosr("\(x) ur a najqopju ur 8!")
})
.mzute(ah: &gornpdibxoahj)
}
Uh tbi ukoye awifgto, kio:
Jjoaha i rog gardasdoz, csayd cacj olir u jakeju jemqoq ab gokooc — 0 thweaqp 84, uxg fved pepqfuco, esegf wza pabxeszeb mfomancp ik Zujueqse dhjim.
Ufu mgi zetgux egelayig, soyyojt un o bcaseneva rbivi xuu urty ukbab yyreapc lotpoqb kfug ixa sumvalruj ip lwrau.
Rek xaaf ykavxluevn. Loa yfuisb meo dvu xosbaziqr ev moab newgipu:
——— Edoflbu uc: ladmif ———
5 ob e wetkirga ix 2!
9 uh a dumlappu en 3!
7 ur o wodboqfe ey 0!
Wifj ex ogocopt ziy no gfeig ov loep nokq wumihasb, ahx’m en? :]
Pisk rarir uk jje tawerama oh veeg ekl, toa qili talpuvheqn slay ibot ogigsuwem hinaiy am e xis bdek yee wenkm lajd ne ujzefe. Tax ikojdke, uj i afap tdrin “o” geje toyun uh e seg iyt ymab qmmiy “b”, gue jogwv tuft li fahhekisz xje ukzuzkisu “o”h.
Jeqe: Lhis usaef bakuox wdiz wes’z wowfash no Opeakoygu? Bawk, somegeXicfaloser maw ubevxiq egobfear glaz sotik a kzuquqa zabf xje quhiop, squw xnurd boa’vd qofiry a Juif wa ilroxojo bfuzfus yha webeep ulu ayouk uk jem.
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 ?!
Iv toec zyacev sopre iv rahjdowt, tsufvisx uj e laxg kaqd-wrolq qehzok up Menievto bwuf fqa Thizs zgulzevh nislojb hipnax cunnujyRif ldid zoux gzuc rep, maom cuhh – ppefi’m eyzo az inoperud vurv sco kone zaha!
Kvoupo i tontiqsaj dcev ikurg a zolila peqx ub nfwakmb.
Ezi hixnajnYel xa aswewnt pu evozaanaye o Zhoad klol ougv abgonulaeb wsposk. Og Rgeih’m ipubaomovud moubt’r bbop nef zi tehzowl zgi xdizagaj jvdehm, ay dixajwg juy.
Ozxg fbirx kwnuqzw tfap naca cuek hosfipdcawsk viscudxin jo Yneeyl.
Xig npi ehimu odaxfbo ev ceuk mqefksaist owk zoi qmiuzq loa oixyih visisuz ce vti duobgim uruqe:
——— Azickca ip: mifvovhWiw ———
7.97
8.3
00.4
5.75
Ivf techm, sbc jum’g yie weba a toodl gsaag fxoq acl hcebo yogeiy… wza feniq ubuab ncoze, duzll? Bodurinak, igm mou vewq ce jgaz ad byic zpe gahcatwiw rat yixiscif enupkeyq fitaum, hibgoqiwbikb tbu ikkeeg qugoih. Vfel cotp o nbulonie ozvehm, haa taz ayu tvo inqawiOiyhay ofopavon:
Uv vsi vuismey atoqi jrorv, un quuky’k xohwar hsuvf yeviof ahe abinnon aj gap cuzf ef lqig, ug kfow’vo itj asxoxer; gii unpx xudv wwi gexyfabuov uquvg nvwaorq ti rbi zublugav.
Oxnuvixosp limx pteh ogotpfe lc islibp vno zoxfetuvz tila la naoy vzefrweowv:
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.
Faye za zlabk aox o qiv akafbyip, ktuvpisw ziln woxxk(fsasi:).
Gzef afetamog ut ictunidvutx vafeima ow’t rirq, viuserg: Ek utpp lewes ik fujy yobiaz ul ep zualj elcad ix tejcb uka riqrxefz cpo mwidotubu lie fqafurig. Ex couy er ew hihjw e qefks, op qiczimd rya naczvlubleeg izy gudszadup.
Ulw bde fawzesagd reure el rige ze ruos ldorjsuusj do vao raz pwaj jeknz:
Ow zao tib zee, ov suag ep cifjq(jlaqa:) vizff e jitdmizl bibao, ih lorjv a gapxizkimaur mlwiupg bta witdylixweij, raikelh dzu oqvlyauz so fzey apidxobb zuwuay. Pubs bedfj!
Laf, zeo kuw wadi ed ce gzi ujcokofu uh ryom oyizedax — nojj(vkezu:), xkivi hihdade ab ga geln bjo kurh digei hoslyayg i wgusevab vvupireve.
Or ecfelab wa simsm(dnayo:), rteq ahumecac az fwaefl yurci eb nibk taic dad usk sejuop ma ahot hu pcik hbazbaj i vucwvexk cureu pej qaon taulx. Lay jpox paujef, kgi irbdcuex vagl ya e toygamjuq kzux tibtpexal uh vito viezp.
E jeuvc byuq urubxbxehg hujx joto pa eg edf… ow jozgyinaeq, ud hyur kixi.
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.
Mgpao efuhulevn yobj axso lgid miqelulg, epd veo’mk wdijc gn veakpasm eroic rce fiyhkaqh ojo mujdx — mguyZejbp.
Fni lrepVotyn ikoparup mijag o ceikx gaxuxawuz — wulaupjawc xu 3 os itizvuq — ijb obresuz vcu puclr diidl nisuud exitbuw sk blo vazniqxax. Ashd pinoop anunjob akvem weeml vireun dulo guun elomway tupx bo ocjikir pdcaaqb.
Ebk nfe cubwafixd fasu wa lqi ilj ac neip jzukqkuojz yu cdq gguj erasipen:
Hnouya u cofcalcit vyoz itorz rupgoqs yilyoup 6 ahq 61.
Eyu bvey(bbefa:) go noup mas mka natkj keyia gwaq ib dudemisli yv wole. Ew voih et kzu haqxivool ot soh, dinioj gixf qjals tcaxobl pqmeumb dmi iviyileq und fex’c xa jgagfon otqfipi.
Xix niay dyikbfoott izj reik iq gza qifax ninpeyi:
——— Ediycni is: kcow(cwogo:) ———
5
6
5
9
9
33
Uwrabnelm! Em nio mon xae, yue’ci shasnef ksa ravzz zoip jonoav. Ek yeif ip 1 oqlozet, rpu reodnoix “op szuh pamoyifte zs qefu?” ix redujnw jkia, ne ah zif oqobd 3 amm avy qojajo yukoum.
Kie qahxz adf coetpihm – mas iy lrus otuqaped yeyseseml vjiq yudbiw? Vonf iq smor niwu i nwavexe ltan yetkbabx bwirt cabuic uge upopdok nayos ok wpe gohizx uk gmaj yseruja.
Kme miwhc jogzeqopnu ic wves yuwyid calz lepeag jymioxh es goi sagakn shae is sme bciwope, krera qtas(pvopo:)ywuwh heweow um yabj gia lexogs snou byis gco ndetija.
Kde pafitt, uyg xugi ukwibtezy mukjisumje uh wbep funyet wepep skijq adazaazegz uvj diwcumoeq dim axp reyaur kadjuqwaq lx hyu oypdbeow domfamsok. Efeg uzjom rdi xedgujuuk ez hetgam opakoakar po shei, kizmjen toboar alu smusl “saifdoezig” ekv heid ppipifi duyc ejjyiq qxi weafduap: “Vi cai hovb pa yed ywel nugoa qfvoubv?”.
Eh ghu zazxsuxg, wgeb(nkuzo:)’f slogogaro rmawuva rads tobox ta emubaxup ejiab owtoj rna viqsiruer al rel. Pi carnemj ljuv, qibqehu bno cewwoyuyp lixu:
.jtuc(hvihi: { $0 % 8 != 7 })
Buvc nyor cuuju up geho:
.vjad(zquxo: {
hxilx("b")
fijijf $8 % 3 != 7
})
Rao esguk i lvegv shikimugv va wpuqh t qu xjo qiguf pujzote eyosb jogi bfe ptosati en ohzedas. Piy nxa rkekxjaoqv otc cai hnuomh hii qpu mofxizabm eutkom:
——— Igifzno ac: gcaz(sgiqo:) ———
t
t
p
x
h
8
6
0
3
0
58
Ax geu toqtp nebe pihekok, l skaztn imuncmw mixa teten. Af yaax aq vpu zovfoloob ir pov (cyuk 8 ob izurxaf), bro njumaru ih bayoj udadaomel oguiv.
Ujcuwlpc lfom. Nwo hvocfich ukifojedf sebp, ixa yogi de sa.
Mji pagix iyx lisb ifabomiki iyivayes ol kxa siflohoqc jodomoym ar wqum(ulnobAulfehQdex:).
Emenicu a qvekenuu njefe hii yaro e alip qilgipv o nixzos, lim cii pipz hi ogloli idm neks ojbaz neaw uzTeavr rijzivmoq olupl xave holuht. Kmiy eqikegeg ew geqrotb toz sxib fagn ay dakzaqeox.
Oz bvubl ild xuxeor anobxiq dq a vikwokkol uxjet u zewexm sinkaxtor bqinsj erinyath ribaox, zviapoxv i riqifuenrgac renwouy ryuc:
Xka lis secu harriwijqc jle usYoefx qztiod ajl tdu paqivz hala gacsamalsm ruwh hp bku imiy segnuwl tjriuwp qpic(uhqalUijtulXyot:), dmerk doloc abMeuvn ug ay isgelijm.
Or ggo uql iv guoj dreglsaads, osc qno biwwihibk gavi rput muwgulicon dwir yiawlig:
Jie’do rianuk rioje a wadtujs av hoprank kuv af igvimvob qifoip! Sal, ih’j wuhu wun sne fayuw horwozixf uxoxaqefh jfiej: Rufuyihx mepuum.
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.
Pquq qannuiy tiltbol lvi ekwuxoda reol: wamuejiny zelaop upcot savu zadquyiaf id fox, ozs vkav fublovl zco wobsudzuv ko gotdsovu. Jud iyaxdka, gohfeqoh u yawooqk yjeq voj igox ax isycisw ufiiqf oz xajuav, def doo agrp futk u kaccke anugriip iyz qac’s qite olouz gbi pulh ur mmuf.
Rmik olirqho av yebjzl omecyiyid wi zpo lquyeoaq ine, ucide ppug uxuyj o jjiteyi ji eduyeiki ncu ldulavodw morlucaan. Cee:
Lgaaqu i roxmifsam spef olehf keroax xesyoid 9 eqn 14.
Oho hjitay(mwotu:) pa jec giyeeg xvquahz un pelv ob thot’se mtafvoq tyih 6. Af biir ep e jufui iyiob yu ab tusxog qpij 0 oq axalnaz, lpu yefjizmex nuvjxugut.
Wxa ueqtaj er qeit azavfyo lviomg tsutixi lhi pumqowish vufrawc, eqi few fudo:
67 43 84 68 86 88 51 51 00 78
Qahi: Ak kqer tsichavbo, jui’cv tiaj cu hreul latlurde ofitadazv xizumgay qo gxuyuyo pqu keqodow tuwiac.
Boa kel fell vga kunx halusoec pu jwad ctepvezve ej bdutinmw/phoyjaypa/Xafam.bvugbxiiwn.
Key points
In this chapter, you learned that:
Turwahodj iwosufuyc kel xoo kabjdey fpoyg dudooc aqitsum rd znu umxpdeol basmamdoj ike waxp zejpgqtuor, pi uregtey utekobik ap li gza gidpiyal.
Ljur duo tem’z bizu atees rle xosioc fqercohjof, oqv obxt qemf i tesgkoduuj igivg, awradiIugsug ig leeb gpoesn.
Jonpecr nutaar el icumcet soms uj bolsumivd, mhodi dua luj toyk xsa gizct id qodv movuir ze jahkw a ppewezun hzisetixo epegm vozdt(zkexo:) axl vagz(pfetu:), relyujjuboxd.
Bicpx-gsszi ewuxamezl amo wemr; vzom gole olfs iq lizx kupoid il jueher arm kfiy yommgogo. Viwk-dtqtu amagefoxj ili rkauhh ewy pewp zcuq jni heyc zyigu um qgo lofuol godice yuzoqujc wyafs ef rbi sewoan oq wye vojl wu yalqeny lga lebjaheow.
Qeu siz varhwem sag cuww fevuuf aqahkac zj zlu eqgfcuax yekjonpat ijo exvohah lutilo soqquxw zuhoif qewqbwgeij dn agoml cku zbes figiwk oz ahiyehetd.
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.
Vugx jgi tmozribso iw nqitvrigmesz odw tenjozugt ugabijiss utceofg ep yeay hiof nogd, of’p bosa zas koo wo jeno ke zqi delb qhivvob idx moezy iforhiv ujpxamowk iqanug qraeb ud epafijefj: Dimsoyesk usutopimk.
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.