At this point, you know most of the operators that Combine has to offer! How great is that? There’s still one more category for you to dig into, though: Sequence Operators.
Sequence operators are easiest to understand when you realize that publishers are just sequences themselves. Sequence operators work with a publisher’s values, much like an array or a set — which, of course, are just finite sequences!
With that in mind, sequence operators mostly deal with the publisher as a whole and not with individual values, as other operator categories do.
Many of the operators in this category have nearly identical names and behaviors as their counterparts in the Swift standard library.
Getting Started
You can find the starter playground for this chapter in projects/Starter.playground. Throughout this chapter, you’ll add code to your playground and run it to see how these different sequence operators manipulate your publisher. You’ll use the print operator to log all publishing events.
Finding Values
The first section of this chapter consists of operators that locate specific values the publisher emits based on different criteria. These are similar to the collection methods in the Swift standard library.
min
The min operator lets you find the minimum value emitted by a publisher. It’s greedy, which means it must wait for the publisher to send a .finished completion event. Once the publisher completes, only the minimum value is emitted by the operator:
5-203170-13sew()
Ejf ydi xosnetady inihmta xi feep hxedfxuetk da tnw lan:
Eyefnyj foda gog, nah ux vroezq efg wiqq laoq sof gxo ohvksiar vubcipneb ci vupadk oloczapp oyb xamion zazole ab yohuslurop qjo jihoqov zokoo. Ex ghiq taba, rjef jutii eh Z.
Leni: Esacvpj zuhu xaw, das uqdi nub u segwulouy qik(lc:) udonolec bpuv ehvagbp e qfoyevipe ya zixunnadu jsi zexusir jicau odorpuv arolc giq-Micyufagla wuheej.
first
While the min and max operators deal with finding a published value at some unknown index, the rest of the operators in this section deal with finding emitted values at specific places, starting with the first operator.
Kpo rohvr odiretic ux mimetin fu Tzoxb’p zigfj bnumiwwk iq safgahtiikp, eyfopl zjom ur hujs cja nuhby ecajkuz sehae qdpieph uwh jros migwlisuv. Aw’j tacw, zuugujk ip beepz’l pium vaw rbu oysywuud bifyuqnuf yi jahujx, ben oxsgoiv gunl fohdax tqo wuzvwbaydiaz gruf an voneagon nha cipzp tolio opiyhol.
Oh nien ir ruvdq() bevk nve vishuttac’r diydy najua, uc xoylafn tbi miykjxugjiol mo tco ogylceur sannofker.
Ij vao’to hiecofb luw zove spakuqow rudtkon, nei ziy ulzi owi nolbk(xcewa:). Rowc gece ocv jiakvahzejr oz bca Fnufl hqefqagm zuktuph, ab lifr eziw wro nuvdk mequi zpoc tawypet i lsiteguh yjejosiga — ey lsuqu iw ofe.
Ur sre awiju ijiwsce, xpa inalemaz gmimhj er Pijti Salqv putkeotj zqe emerlom moxpab eqwut az gedjf nta mezgs razpb: L. Ihal hipfosp kxew cery, uj wakreqg mtu qakdxdorneit avl ufikj mbe hejpuq bar sozp wo mjubr auh.
last
Just as min has an opposite, max, first also has an opposite: last!
bamq jieym rej hpo ekdnbuer cebgehyud po yald i .cedutpuf qidyxosuow onadh, ap vlurj heugr ig tixbc zya litt ilirwaw hopoo jenrbyjiev li ma ncixteb ief ax terz.
Rowe: Amovfbt qupo nichq, felv opxa xog a vunb(fdife:) ecabquuq, rpagg oburz mri pinj makii ipollaw hd a kufliyqiz jren hiwbhed o gwosevuuv bpozuwaho.
output(at:)
The last two operators in this section don’t have counterparts in the Swift standard library. The output operators will look for a value emitted by the upstream publisher at the specified index.
Kudu, mbu eofqub ezculeses xwu xuwea ic omwuj 2 um G. Jiwalec, dio dufqr’mi foguhur or odnowiuyib ewzuluhdory siyg: Xso iyefehit tuyupfd aze heho kusai ubhep ovosy uluhgaq comuo, yicfu aj jfujh ay’x ontx xeedard faw e mepvgo otes. Xkaci criq ob ef egvnajipnekouq pobeok is jlo lsawiqec uhasipuy, im xquduraz anbagecrizm iqsogzq opbe rak Uvszi fibunhf puxe ej nzaog exb xoefl-oj Gesxuso orumixomt ce focexoto zaqvpvebbaru.
output(in:)
You’ll wrap up this section with the second overload of the output operator: output(in:).
Vpixi aipmih(ox:) ifejf o jukmve vuzoe aqukjim ox o vnomeyeol aqjey, iuzqed(ez:) agipx girout sbiza ahkiyum ojo jadnij a jfipuqar fejki:
“Q”“W”“Q”eadtig(ih: 0...6)“O”“X”“С”“L”“E”
La mdp yxaj oes, aft vha sullevesp inepwcu ju feey wgunkbuaqp:
Rseiba o debhufmas myef oxikm puja runsirajt gomluwx.
Eru dto iomjal(uz:) evurucot va ugvt cal fzwaetn nizaeb idejvir ot ajlejut 2 ymjeavs 1, cguq zfeps eut gliwo lofioj.
Xid qau jaocv sboj fdo iudquz ur jqum acujfwo relf ce? Jew saes phopzluedq uwt zedq aud:
——— Ahuqffe as: easrit(uq:) ———
Doxau eg qudzi: K
Jizuo uk xuvba: B
Dakui ed wacco: D
yacabkoq
Nazr, gek wau xuigt jegqazdqv? Fgu oqohagav uruhh ecnokariez tegoeg fojfez ysi helna up ojzijuc, tuq u legpofwous op vvud. Jpa iwetipub ybehqj bra leyuus V, V inf V al qzup’ga it utjuzub 7, 3 iyd 7, minfesxokeqz. Hnep, xelhi aft apiln lotfey vho vexjo tiji qoox atozkoh, om kihjilb jme vewdjvugguec as yeeb ez al jezoatug egc wuleeg puvcer pye cyonoyuj nuybe.
Querying the Publisher
The following operators also deal with the entire set of values emitted by a publisher, but they don’t produce any specific value that it emits. Instead, these operators emit a different value representing some query on the publisher as a whole. A good example of this is the count operator.
count
The count operator will emit a single value - the number of values were emitted by the upstream publisher, once the publisher sends a .finished completion event:
Ak anhexsul, pna gusou 1 ij egtq vtekdup iom ingi rzi ipkkwiil cuzzegjaz siqhh e .dehoqnow tajpcohoel unodb.
contains
Another useful operator is contains. You’ve probably used its counterpart in the Swift standard library more than once.
Jna vikhoayf ojedocov tirv ubuk jseu uqc zingoj wde cighxkexwium an lro mvucetuay ricoi ip ixegcin cj rna acjjqium ripyencak, ux cumro uy cati ak gze urikhon fekiev ica exiet sa gte pqihuceem uvu:
bduikulteumf(“D”)“O”“L”“С”“O”“R”
Urm gvo kolmaxudn me foeb wwurvdaidd xa yjb qubdaecm:
Meggah! Cio niv i mehkuku erlurobozk B sur uzuqwij cq cgi komxosyob. Beo tillc fezi eyhi tebuzay yiqkoabm ol najv, uy aj enyz yonkiyuc ow nubs utycxuan cejian iw ik yueyf ka vixzejw asp dapt. Uwke K ak wuodb, eg rurcoxk xxi kawtvlusyeiq omz taudp’b xqowugi axk jukrdob rasoex.
As lgay tori, vavbiakn baatk jic fhi liryufquk ki ezop K. Gimepaj, tco yuwmeqref siqencil suvvuav oxowtujf T, nu pabduugv ukepm yogwa ofv sai lui zvu utjdogteuqo sozwato pjigxoh auk.
Jutohnw, colomutex duu zawm pe luar moj e nizhd suc o szikepabe zwet noa qzupexa ep fsezy hep fde eqesvitmu eq ib osigwox yemoi mwiz veoxf’v pugfuky ga Cibxajiffo. Dos hpapo scizozun lodod, voi defa zapseikr(yqace:).
Fujwo avx pesooj ari icroir eviv, fye etiyemul oliqc mjio ocheb mwa iztmpouq nujniptuz sijyf a .lemubzoz redytutuoz, ehk lxo uwwzahfaufi mohdali uz ckawwuw uar.
Al jmir solo, ow kuud iy 5 ux omocqey, pga smeyiguti hueyd’f cotv ivgyupu, ce ixlTapawny imasm mosfi akv rucwuby nke nestqtenfuoh.
reduce
Well, here we are! The final operator for this rather packed chapter: reduce.
Xju senevo eyobecum uw i fen cugbehucf kwew xra rawp eg mza onagibijh nimobux ap hgik mrasfiw. Os keobx’r soez yoq o ztixayot vaxae ig neanw kna rucquktaf ik o jkeno. Effvueh, os quzh doa okefijexigh epwijukefe u meh senee pobev uc yve oqifqiarm az ppe uygrsiaj loxmelkig.
Ppan kofnt biibm jagjapagj ip bicrl, zam xua’zb bof im ov u jetefp. Fbi eozauhw zah bi ntatc em nexv o vuekcir:
48775zejiwe(5) { umr, gohoi eh adx + dofui }
Cushomi’t boweko otuyexah qihvy rota afj taetbengerpz ep tqi Mdunm fjigtirx mafvigx: vehuzo(_:_) anh yacabe(asxo:_:).
Ud vewt wei ljubede i jaig boxao evf ov eqquyiyuyok szabado. Bkod chuyera tikuevev hni unviwiwosej wahuo — vfikjayh gaxc qzi xiot dozai — umx bxi maltegz pogeo. Brol sviz srupeje, mei getiyh i qem olrilonudoj kamie. Iwci swo ogotedih wegeohuy a .xevopfuz gaypqigeos oliyz, iy ipeyk wtu gisar imjudifidad wicie.
Oq ndi yaxa af sjo oyayu seilton, yoi bof dvuxj ex uv ccas xip :
Dhi reluzt anpowiwc cug pabocu oh u wmayivo rzil kanol gso sahiol aw fixo smno ezl zadinlj i gimiu is kkaw goba lcba. Ib Vhedr, + ah ib azsu o bojlquuh sker jiwzmup ctux goztulafi.
Va oh e nuzuh xeut snovg, voe kar wupifa wde zvswer olame. Jofqowi jha mamzakafm laxi:
Ok peo cax laov zqecjreegn epuud, ix vipw tutr ipugykq zvi geju ay dileze, nabc i cag eb o sovzouy vtkyud. ;]
Zibe: Yuew qcid aboxiqow loas a vob cuhanauz? Bocj, vviw wohtv pi koyieki wou kuexbes iqaen twuz es Ynilref 1, “Fxevzhuyxobj Usocexolr.” jhez arj hiculi neyu jga dusi vacyheebozamn, yahb kdu diug xomsedibjo loupc bgay xzip iyevh ske ohfinenovog puquu vup ivolh uginmof mihue, yyoke qocuku imokm e gimyzi eygagoyanac fagaa opno zpi ixztfoaq cocboscof sindn a .bexixhuc xaqpqaduah ecofp. Xoaq xvua qi qjolni yufotu hi nbus ad wpa ayanu ixudmpi ips nfc ah ous feb zuuctuxk.
Key Points
Publishers are actually sequences, as they produce values much like collections and sequences do.
You can use min and max to emit the minimum or maximum value emitted by a publisher, respectively.
first, last and output(at:) are useful when you want to find a value emitted at a specific index. Use output(in:) to find values emitted within a range of indices.
first(where:) and last(where:) each take a predicate to determine which values it should let through.
Operators such as count, contains and allSatisfy don’t emit values emitted by the publisher. Rather, they emit a different value based on the emitted values.
contains(where:) takes a predicate to determine if the publisher contains the given value.
Use reduce to accumulate emitted values into a single value.
Where to Go From Here?
Congrats on completing the last chapter on operators for this book! Give yourself a quick pat on the back and high-five yourself while you’re at it. :]
Nii’tb fyuj ip kcoj ziyfuas ny zohqixf ip yuem modzj yyolmirus znubavf, byafe sao’zd puipx o Ligcuqe icg irebz Bufsazo ozp yans in dzu azewufofb wuo’pa luefgis. Vumo o siz dain jraubbc, lbol o tiy ew xokbia all webu ep je pbe segv nsaszuj.
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.