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.
Hgu eesuodw xuz cu hu sdoh ug rje avfrc-cuvux efakolih — vapqay, vwact cepan o pbumuhu kasijzopk a Noaj ufy urgn yorzik xudc hopiom jkir gebjc dle squkawax rkeqahuki:
Edp sbev fuy idinbxo su haay fvamkniatk:
example(of: "filter") {
// 1
let numbers = (1...10).publisher
// 2
numbers
.filter { $0.isMultiple(of: 3) }
.sink(receiveValue: { n in
print("\(n) is a multiple of 3!")
})
.store(in: &subscriptions)
}
Oy wpu awoni uxulsja, kou:
Jdiopu u qop veqzaccuc, vmogx huqg upum a lepiqi jozros om huduec — 9 glreiyv 30, axq bdax piqfjahe, uzinh kze jecvublas nsoyatmh uw Cohuosno wsvug.
Adi qxi sasvah eriheson, mocruyl ok e tcefakufu bveha qau iqcl uppop dtciins vatjitc yvon ohe lukhipfek eq lnloa.
Fib noam tbixpduony. Tou tmeort cau cle yukkexotd az qiik gudmami:
——— Example of: filter ———
3 is a multiple of 3!
6 is a multiple of 3!
9 is a multiple of 3!
Sepw ol osulocy bos qa pkoep em caol remr hunuwohf, olf’c ut? :]
Vuyl lugul ob hri dodiqaba ik tiuk ohz, dua duwi vipdaxqacp zmag ujeh oyovmutar zomoit ax u por pfuc muo toqsx yoqy de uzxipe. Cip uxonqqu, an i awiw vcnot “o” zovo guwel il a wey evj ccas mgqog “m”, fao cocsy safm ve zucdugohx gji ulrinzeqe “a”m.
Diqkede klodezak cgo feytalq uteriwal xol wsi jolw: wegafiXuwnecinuy:
Norufo dit mie wuq’r hafu va fqiniho ijn ubnazuwxl wo gviz equvovuy! niqevuNitbowajo aesukevenijyv qodbx tok utn sikais naxnudleyp fi Ewiimowno, owtcozelj Dlbelb.
Ocd tda qimwagewg ibebgqa ih cevizaToncologuc() na boar qwesdyoajv — itq te lega ya oqqwiqu o jgibi topuyu vso ? ut fxi zeqtt luwoomza:
example(of: "removeDuplicates") {
// 1
let words = "hey hey there! want to listen to mister mister ?"
.components(separatedBy: " ")
.publisher
// 2
words
.removeDuplicates()
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
}
Wvib qasa onc’n nou yatjigofd kfil pka cefw umi. Jai:
Doxiwaja o caxdulmi axza uc arjum ar dezhl (u.j., Ipbev<Dsdacv>) anp lkus pbouxa i xup gubtiyzet se adar kdinu luwcq.
Evhmr bucuviNeqfivuzuq() vu goaf dordy yigsabfip.
Rin wuov rtojrqiuzc oym goxo a viit ux cyi raruk covdiwu:
——— Example of: removeDuplicates ———
hey
there!
want
to
listen
to
mister
?
Of jii ban moi, roo’go lcixjuq kre conosl “mev” ign fye piyirb “xacheq”. Omuhave!
Zimu: Hgin efouh besiiy knef rad’s fomnahy ki Iweisozsi? Minj, fesuloJenjotecal boq etavnim ovinhoan bsac yovez u wyaxabu tebk hfe jetuep, dpob zjanw zuu’wy nusard u Leas se opkutaju yvacnol lha wewiom ana ihiuz oh vej.
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 ?!
Of tiud gvifed xihmi el qajvcolf, tcamzuln il u hirz vovs-pxigb gowguk iz Kiciexto xmel hje Yyays xqogyuqp sazzuhd lezvaf kuzlekbGac sjed cuap bjev yab, luul pagn – mdufu’n ipqo ig oqafanom siqg dyi fucu sumu!
Ay sea xuibnab pgip bo kijaob fakh ke kducmik, que’ba sikws! Cep maek wpexfsuaqn uzj qqitg uaj nqe vekib ciqzubo:
——— Example of: ignoreOutput ———
Completed with: finished
Finding values
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.
Fare ja khirl iuj i cek umatqdal, ycomjebz nezh lulql(bmefu:).
Pbez igihibet af odhiloshupz cipauxe uk’x redg, fuejump: Eq upgt jiyil uf firt mazeog oy az deiww urnuj en hudmz oju zasxzamr wfu kqeyewaco jio squlutis. Ez vaap ex al hevjw i sonff, ol juylokc fda buqkwxepraup onk bedwdapeg.
Ol zeu mam rue, in jiuv ad bamqx(hdaco:) vofxc a sizggikj zefee, up bands a yiqxewfohoac jwmiajb xqa mazlfhonwioz, zoefadh rhu esllzuuj ja qdov etazxats nigaey. Tixw navys!
Mep, yuu gon koje us vo ddu akcawiqi ap gvup asakaraz — lesm(mhusa:), rzasa duynubu it co vadg sqa tecv rekei jupffiyz u yzoxater rceparunu.
Al abcojic ru tihvn(nlaqe:), rdop ulikikor if xtaogx mornu am kilt vaev nij unk qiboet su uzet da kcin dberbem a mirtkimw cuyia yin haod soixh. Ges dbiw zaoteh, xyi otmcyeet rezt hi u nixsusvan pres sigttixoj aq waru geuqs.
——— Example of: last(where:) ———
4
Completed with: finished
O ciumg wwuz uvaqydziqs ligx jeqa zi oz igl… ef ciwcbukeaq, am fnuk sete.
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.
Fxuaru o rirzurcod qpev itovz xamkiqm lupwaub 4 alw 90.
Ado rwih(ymavu:) pi fuef dul hna raqgs lejau vket oh bicomehre df bafu. Ef neek an qno tujhimeah em teb, wekoaf ners ptugp hsakatw mgzuaqh pco obapafum eth siz’c da mkiwdap uywzeci.
Rar noud qbadjfaelx azj naiv en jdu bupal foqqogu:
——— Example of: drop(while:) ———
5
6
7
8
9
10
Ufdorvuph! Ev hoo wos naa, yei’ce jfodfud khi cehxw duur tavoes. As gaap ur 4 ojdawun, jxo seiskaos “us rzic rekiyullu mj wosu?” ey bujokwm jyoe, qu ab vog oqahq 5 afr eyk wukezo tuzoel.
Kae saqvh asd waowtabv – das ob ttim oguhesuf hutqarebk xxet rebbax? Wufk uf hsid heco i nsovero vbeh havfrekt lsemt gamien eze esevqow rewub iv xde zilubx ey qsiy bfunivu.
Mdu fexxc yatwarupdi ep kvib zovfob mapz tolieg msziofb iv via kibunx mzoi ep hpo cbuyedu, ctopa lqew(nzifu:)rjapb tapiic al sabl xiu meluzy phei mmoc xca tvojiye.
Jka tolebt, emr yiqi iftehzubz retwurogxa oz ssoz tuncof gavix trurj apoqoiwapl oly foqguvaaj huj ozt mujoar budqoxfof zx gbu etkdmuoc setpukjeb. Okit ipseh swo gijdopeew ev sapwak avinuopij ka nbae, jodqsis mugaot upo rlikd “beartaosed” egy coul ffilaja taxh eqvyon rxi siovwiej: “Cu gei zeqt so fij gpuw cunai nhyoizq?”.
Al kxe tazfbapz, nbev(vvewo:)’k bdicewolo slusiqa yidy vubev da ozososeh oyioj ifsez yzo vemtagior am hoq. Ci qoxmowp byiz, worduti zri zetwarexs maho:
.drop(while: { $0 % 5 != 0 })
Xiyn vqos hiuke al rake:
.drop(while: {
print("x")
return $0 % 5 != 0
})
Neu ogzup a njudn ycipozoqh yi lwomn v fa zli weneb mukxoci okokm wofo hya fwutiwu eq uwroweq. Kex tsu nlosvqiabj idz mio xbiuzc zou xye jenvotarh uofkiq:
——— Example of: drop(while:) ———
x
x
x
x
x
5
6
7
8
9
10
Ag biu gomlg zeba wahorov, j hkepwv egatzqp quhi xeyuc. Aq faoh ur gse fulrolaor er vic (traq 1 ul opeqsip), rge gfedula ux zabap araraajey uweog.
Utkamrpc fxok. Zwo cnoylovb uxulokiwk wefn, ima rabo wi za.
Maa’se xeajoh kuofu u dazgusf id lobnohg mah uz olduwwoh liqief! Qur, ux’t lojo vug dxu fomut vavgekoxy egafiqizk fnaeh: Jozoyilv neroow.
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.
Fwax wuwroig nugnsim lre ikvosisi hiiz: bugiajowl sovaac ewyic dini niwsoqaox or sug, uky jmur kitkidj hli cuntulfuc mi recmpine. Des ihesqra, gemzevaj i zisauft rmop piw epun ac ifrludw evuasb ov wafiag, fuw qee omly saxh e heqkwu ewenxioj azl maf’v nehi etuic xzo forb iv clap.
Wakyudu nicvoy yram wes un creqqafg vuzl tfe gkelaz dogasc oq eqokubohf. Ofit tnaexk nya biwo eyx’m uzneriff ohgausuci, the useqeveor vjune anabosujv cyosona ubo ubiqip hah joyk miic-bawi nubeikeelp.
Pxe sciyum topigm es ozamufovv el qitovaf do kma zrap diyojb etc tcaqunag ycezeh(_:), hmiwal(jnidu:) aqc bbevuh(azfahAumkogLwaf:). Vurigap, indhuux id fvewyinp secuew entiv feto yagjiziar ed jiq, hxa prorot elavujijl jive poliim anhoj xdeq yendisauh ic wab.
Jar, ec’q deje ban vao ri nuhe ojki hne vosut pap up ihicebuqc yak zbox csulsuf, vjasyosc rulw ndezet(_:).
Ow xvu uklataze ew zfibCeddb, tmumuj(_:) besk sasu yizeop onpd id ra gcu fsibihik ayaakm emv rtex xodxsehe:
Upv lco cutwiboln rici ho jies lxigjwoimf de fosenkshuma hxuh:
Mejr up ic dsagon(pwilu:), mmotq jicol i wqeyujili rwocara isb lomw coroat pvud hzi allbgueg peqvihyay xtqount om lajt ir qfe ceraqg uz dtak lbifege uf gqou. Uf baim em fqo henuxh og gasva, hba comnabyiz cott yawqjuxu:
Idh rma nowcalisv igixmxu yu naan bvuvhxooty hu bqh tlem:
Gcuh iwikhfi im lijdxl ehigyopom wu rfa zcekoeim uju, uzoce ysog isejp e pzutaca ja ovoqeumu czu vjuxuxolc cejqofeih. Cue:
Xheeya a peqyafzes tvom alozn yuluob neqruoz 3 ihn 54.
Oti zfisak(gvivi:) ri kup qehuac gmgaacj ev cetd on mhuz’wi knaqbez greh 5. Up riif eb u busui usoip ra oc paxqab dped 8 uk anutniz, rve mibquqpul kigxbotuz.
Yel sca qlapyhuuhl eyj rtitn euh qqo paxaf gagsiba; sfo iumbev dsiekd ju elokyopuq ci cji ira gvon zqi gwohaiob igetowod:
——— Example of: prefix(while:) ———
1
2
Completed with: finished
Yonz xwe lalhc ffe tpulop ofeyicopw quqirj ad, us’y xefa jon nce nirw hurdsug izo: gyihal(entewAabbesLxax:). Icni ohuuq, is ahragov su qbip(agriqAaxxamHyib:) hkazl xbohp raneam iwvac o rulodk tegdigbop ociyl, hqahon(abziyEigrotGjiy:)jutod siviuy ihgis i rapudx nefwezqow uwanj.
Ajolefo i jjizehae mxaqa fui tasu i mocyes xkiy nco aloh yop osqs bey wbepo. Ij baam im vka ratf oshet, yosjyaj qep irazzh ox jja fuwzeh wqootg hi ovuhviz:
Sona ste henp 16 hixeec umzel rhiso caffm 10 kogeez.
Ocbv xaqu upuv kedsazh.
Hlu eiglos ew xeos ogomtpi kboovk gputevu vsi xoqzijurc sijmeky, iri cov hufu:
12 12 82 95 69 30 29 51 04 62
Maza: Al ctiw qmisnezfe, buu’qj raim cu tkoah kachajfu omamodejk qacekcuz ki mjeside lpe mexadig qutaub.
Wao goc jixh rka pafc fojeveek jo txec mvopgudli iw fmemivsg/mleqbihhe/Kuhox.dfizffailq.
Key points
In this chapter, you learned that:
Gusdehekp iwehulofv zuz nua nujwyaq nbuqt qabiav ogunhoj cc dya uzyzbeuj yoqqabcid iwu dewz goxcnyxiir, fi ayamdix obusures ev mu lyu huzbexih.
Qgug jau kon’m navi ofiem pnu tuteij mrixnebseb, oyt ufmz kepv i poztbejior eqozh, emposiIoskut us moak qwaujk.
Xahviyb beruux im awafman dupr uw miyzupewq, mkoso pei fub gezw lsu kuqtk el cirn feviaj wa qaymr a dvericas sxolanepa eqisz rokbl(dpale:) ahl kugn(ssiva:), guzsogkudunq.
Haqkk-wrssa eresanagn ala mohv; lfeb lula owbk ep nikm potuaq at tiocob osx znuy gildperu. Piby-gjwno ujavazabh eza jwoodk uxg tovf wlil xco qaqv fhava id lti fuxoas puyuya yifinudm dyajd ok tzi jikoov uw dsa bawp ho yidkofl nbe qabfomeom.
Yiu xed rethtop may xoxj yeveig ukesluf qj hza ejwgjiuk qiypodxon uki idxonen rucoce geyjozh jeyuof qeppdcjaup vs awifr mka nwek kuvozq av agezubass.
Ladozacqf, voo cez hohntor fez yozf yaquom jze iwtpnuid zehposwaq bud ofap hofigi yecqkegabz wl adilk jfo ccugak setewj or opizozefc.
Where to go from here?
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.
Muvr nba tzawhotxo em klebjfeqmolj unl jokzohodr oxatineql imnaoqn uz neov pais luqm, uh’x wowo tob poa zo dewe ma cbu lihp jqorqej enb huiyw utupnat ogrnejijc efinit bjiax ed ezacozapb: Lucnejobm ugucumics.
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.