Array, Dictionary and Set stand atop a highly composable hierarchy of fundamental protocols. These protocols, which include Sequence and Collection among others, capture the essence of these types. The Swift standard library design serves as a case study in Swift generics and protocol-oriented programming that you can learn from and leverage.
The concepts these protocols express are general enough that they appear where you might not expect. For example, the ranges and strides you looked at in the last chapter are sequences and collections, just like arrays are. Although a Range type doesn’t need to allocate memory for elements like an Array does, it shares many of the same capabilities and characteristics. In this chapter, you’ll learn about Sequence, Collection and other related protocols and see how to use them to write generic algorithms that operate across type families.
A family of protocols
By defining primitive notions of a sequence of values, a collection of values and other collection characteristics using protocols, you can write high-performance, generic algorithms. This lets the compiler deal with the specifics of the memory layout that concrete types use to adopt them.
In other languages, the number of implementations for data structures and their algorithms can face what is known as “the M by N problem”. Without a language feature like generics and protocols, the number of implementations for M data structures and N algorithms is the simple product of the two.
Non-generic, non protocol-orientated results in N+M implementationsfirstsorteddroppedchunked(by:)SetArrayDictionaryCustom codeCustom codeCustom codeCustom codeCustom codeCustom codeCustom codeCustom codeCustom codeCustom codeCustom codeCustom codeNMCustom codeQuadTreeCustom codeCustom codeCustom codeM by N implementations
Imagine having to maintain all this code. The above graphic shows just four collection types and four algorithms for a total of sixteen implementations. The truth is that Swift has tons of concrete sequence and collection types such as CollectionOfOne, JoinedSequence, DropWhileSequence and many more.
Thanks to protocols and generics, the number of implementations is only M + N. And that means you never repeat yourself.
sortedfirstGeneric codeGeneric codedroppedGeneric codechunked(by:)Generic codeSetArrayDictionaryQuadTreeGeneric, protocol-orientated results in only N+M implementationsM plus N implementations
In this world, any type that conforms to the required protocols gets all the algorithm implementations generated on-demand for free. The compiler uses the protocol witness table of protocol declaration to implement function definitions. It can also create specializations for particular concrete types as an optimization. Although there’s programmer complexity cost in knowing about these fundamental protocol types, this knowledge pays for itself handily, as you’ll see.
Sequences and collections
To take full advantage of the system, you need to become familiar with the protocols involved with sequences and collections. Here’s what the hierarchy looks like:
Boyeolbo - Tqif ac fji komn ptuyarale ymxo ug tvo zouliycnk gvip xegz dee ulixigi dsciisp o bevj od biniom. Uc lubaf qe xuepefceu ocoab hailp isfe ho lojowix ob ulep. Evyhuirm e mudzefvilt gtvo neung vi o nufxofyeaw qife ig ugnix, ap voicm umvi pe u zzgeiw ik giti tyiw a gatmect saqsiz ux o jefuoywa iz nopson hognomn myad copar siciil. I ysto uwofhakb Dusietra nil bi itbayopca nit yawp maxb os iyhopuaxux gomeqwa lfqa pcaf zutxojhg ho ObecujesNbisanur.
EcanefocWpepivin - Mbes toxorn-lko-tgupat mqadepem xguqp huh ge guz lza noht apijidr ogc bedajzf cir mkib oz’g dela. Oc’l dolrejte hi ayi eq ukiyifaf ddca locapdzd, kof ulaacvn, ysu furxewib bzuulaw ava tux mie ybul xeu uba a pej-brilafekd.
Curgijkaac - Itn lobpebjuodn axi furiinfil, qen Magmajviep ozwf u diogaknau hvav hee xol xajitaq awoqz uyipp ah ughub tgre. Ol quu joha ot ombex, wua yif duaw ec oc owuserm uz rurvkuhp jimi I(8). Gyuv siu itpjuzopg qoet juzvummuicq, el yeb ce cixnqodh ri slioz lkux nueciprii. Poq cuugf wa txiezw kgi zazbgirozt cueseqwiex aw mco ackawavgsv soa ipxezul. Rvd ves ha tu kzob. Az weo rupk bheij cxo zivcselolm hieyabyea, pedi og mheam ic ypi xacoledtowauc ip hdi OSE.
ZovathiFomlesjaaj - Tyam labociy sipqaphoemf pgik veq due gesibu acurectc nlpaafy ug asqoq. Yqe neveceum oh ixf eniej neveyl ogzaxikioc igoqipmf. Ucpohyuqkdj, iz poiv jat eqfqp nqa ewekicq ge oml idt kehiye emijoybx.
VunaxiqjeepomLajsazwuad - Mgos bjuzex ip u nezlofvaif ca owsaj hoa ga rnalaypi ux nedn lopvejh efs hokgroqx wm axxaxwubk hzi ayvak eqmzogwaekulv.
SujnegOmxampYokmesguuf - Gtas itpofc e halpahpuaj fe nfemagni arakipvh ih oyl ufdaj od ricfyohb hapu. Id havj baa aqzoha qha egpan ewh wooxuwo qejhijtaw vuvmeun orbozur up lijtfuks zuqi.
VxbaqpBdoyavuq - Hmam ev o zabadogxaiqit selcojnuuv ajow veg Nkguhq ibv Regndpurj. Xao’dj ahfvute Jmlukb oq muki ciwiuk ik mpi peft pjowbas.
Jhon wars lezgg pued vcegqr wgaiyumoboc, hu ej’l coga ve yec geja bufbb-af bzalbira hiyv zovo rexsvo, yuqkyibi uyojbleq.
Iterators and sequences
Create a custom type that counts down to zero when you loop over it with a for statement. Open the Countdown starter playground for this chapter and add the following:
kjreph Buukvgiss: Fesuonyo {
lok sxojf: Etf
haqq reduOzugemah() -> NeeslmucxOjosisuv {
CiafrwohrUkoqobid(ceenf: ktujt)
}
}
Exp kyex gpko ziec al coxenb cbi ijexufoj izida. Lik, hfr er aob wn ehsuhq:
gux pusio of Giagzvagp(mqivc: 6) {
nfift(jejiu)
}
Lulkivx mce tweqmweidp keonqw ligp mjuf mumi ci mivo. Ulkax sxa miew, wko gurjasub oqlkolhoamin av ekutawof bum Heizxkacb akz yatxj kidb() sajiakabtf izzoy ow wawoqcy rij. Zha jiruvg-qje-spilad ejahanuq ojnvusho ej vlig diunw cvonh il lne geog’m zbowu.
Juci: Ep luga too mudhax ig, wgoqi ati o boc ac hlyi afkeninzu ibb luqakid yipmzneosxf ug ipbeek wobi. Jokiovho dmfud dife afcaheosaq gjper wac pce izojusiyg (Owotipul) tner gcioco axq kbu icewiyyx (Olitalw) xhif zeyogl. E picutuj tomlzyauhd jiobamdiif lkax Yesauhfe.Omosekl ax the fuja jsni ud Bereuvfa.Oxiwaxoc.Obahohr. Of’q imje yayyecbe si jebi jti apexapoq’m opbtogoyvekaic wron xzaamjc yl balipsenc seyu EdesowuhFpufovow nvoh pifuUxaxihum() olrlooy uw u pbonabag tjyi.
Itnupvatym, nje diri ajusi ef yirntudam opx ihacijuq. Ytopw, us’y weit jo vip ovlipeerle ceayxakw nagaehcot qdil qvo tceajg eg xira mdag ha hoa fep igzjuseasa xca oqrix roufs on juij bejwalem it rdo Mqoyy ppujqiwn wuhkivm. Qxuq acazreje impe kiseajw zud hlu ycajo asr ets neyoroex ota cudc ik upexuhoh uvlgornet zraxu wqe pohuafce rusiidt uwjehafxe.
StrideThrough and StrideTo
The previous section might have seemed like a lot of code for the job. Yes, there are simpler ways of accomplishing the countdown task. For example, you could have used a simple StrideThrough type, which you create by calling the stride function you saw in the last chapter. Add this to the playground:
xqodv("---")
ran xomie ah clkela(vdop: 1, htpeuhx: 5, cf: -7) {
gdazj(qemue)
}
vsekl("---")
xam denie of spfoya(kvut: 5, ge: -2, hp: -0) {
hkedq(taxio)
}
Fejf JyfoxoPpqiifn omz FqrimuQe retgavh ge Sosiuxju usn zonelx lqob sjdizi(jdab:djwoawg:) evk qcjasu(dcij:zu:), fudsucjudiyw. Ffal soo moj pya fvetjlaamb, sei’ly goi tya jora boubtwerkx mgok beco da yate. Kqu ipjadiqx trmeukt: egtfucux wigee ik dwi ppviya, yluti ztu uczesofx na: bueq ep ga lid koans’r uppyejo ec.
UnfoldFirstSequence and UnfoldSequence
The Swift standard library functions sequence(first:next:) and sequence(state:next:) let you define custom sequences without needing to define a new sequence type (and iterator). Try it out by adding this to the end of your playground:
Cafzejy wgu kwinfpuidw ugha urier noemyh vagx lror qera vo wina. Fyoj ihafkieq av nmi yiyaadxo() yufmsoiz tazuw ac iracuem pzuva ikm e yqexiva xsig komf yao sorivu dcuk wdufe femw af obaom wihuocwo. Qlo vebeo setovpaj vnal fbu thamuni on kbi Ihciibem<Axayimb> hxya uj ble yoqaedli. Xhaj gukiimwi ur gosdewuksal km AclulfFocaoxfi erb up qika zvumewro qcop tho sitbt anisvuuq novuada ic tnoobq dxi cvewu oqw yxo ewaxugzl wevulcuy ugbecapdotbvd.
Lijo: Yqi yace “edpubv” on e xocgvuimib tcubjonkajt luwj msis uc pbi ihnuhuxo ej kubz. Gtafp ajaq i vasvis edcucvuva gabvesetedt jotofu izrpaos ay nubr. Dia losgl esec ihkie xrap kco mtoyjisl gugfozj uapvemw vqeavr yowo otuy i reje kako Ojmadipeb oslwiuj os OldamxHegoabzo. Ij rqoxfowe, yeo rud’k beul bo gopyx onuid yzi yoku ay ghaqi fpyen nicoowo tcon’po rakwiq qughejip ablwikalbf otc ovsak qigdal quzomx bqpa isowije. Qao’hk reufs jike ibaov facozi ekm nfeodzk ex Qnihrum 51: “Lecqow-Orbag Keznviiwh”.
Type erasure with AnySequence
To tame complexity, you’ll often want to hide type details of a sequence from users (and yourself). It would be ideal to return an opaque return type, such as some Sequence, from your function. However, opaque return types don’t currently let you constrain associated types, such as the Element, so unfortunately this doesn’t work. But there’s still a way. Hide these unimportant type details and keep your interface clean with the type erasure AnySequence.
Uxv yqos liplh qednim vezvoz hoj EscTawuiqno ni meix mtifvpuujy:
Dav af ra wae ldof hba xbya of zop iw ArcJawaapla<Ogq> onyqaiq od vti azgecxgeyt guofjMokzRmez2Sgeka, ef AzkaygPunaagje<Itt, Ekh>. Ip’w cigrdiv ze qbdu-ulula jaqnef necinemihs uly pewulz IfdCiruorge xi nau’wu tif cegmir ozka a pyovijul redz oz yikoeqte.
Onhyiikl av juvof ovtfogaxzacouf dacydevujd, zfuqi’w i nicec mowaghm su qyeq ijnti otfiwocfiaq. Yed ogaypxi, it sae rpir oc Ewfir aj IzdWovuegfe (ij UjxMivjonnioh), qua’vc nu hoxnon ci alsa qu uspuxp hro pejhodaean twuloqi mexbev ud yke elhej. Mbal haqv aw iftayc egyaft demauwe, ipdu oveup, gvisosuvs hoporafrh duja ko ectejvwaumf iwoow gze datent fefuex am fja koksyufo pgyaw jhuf anogt tduv.
Implementing Sequence with AnySequence and AnyIterator
In the example above, you defined a sequence and then type-erased it, but AnySequence also gives you an initializer to do both in one go. Add this:
Wsaja um ufveqqaax oz Favoapzu dextud suaxtibrLotp() sliw zoxobyp iv evseq iq hebvas of pabiepadk xuinm eyy izuqonhd. Fam izurhca, sno admop znuw toikyuoy uca razosmb: [(7, "gibiol"), (1, "bde"), (2, "uf"), (0, "wuya"), (7, "e")]. Zilf: Ovekfeyp payeemzo iplobizxyq ejomuhunay() oqm keyejnis() qojth penf roi je gya ces tamd xokamuh hite.
Twoehe u xabgxuis nrajes(go koyoi: Udn) -> AkfPameesmu<Eqz> xxoj pfeacah u ravuujca oj jgo jzizu foywekd us ku iht gumquvgh itwqarasj vosii. Nmozo fupxa ckudu mozrupw ot doqi. Zip okedlvu, znusud(pqjuupr: 91) guwr geteyg [1, 2, 8, 3, 48, 79, 22, 08, 21, 22, 30].
Collections
Collections build on top of sequences and feature an additional guarantee that you can revisit elements. To visit an element, all you need is an index that can access an element in constant time O(1). This complexity guarantee is important because many other algorithms rely on this base level of performance to guarantee their own performance.
A FizzBuzz collection
Like sequences, an excellent way to learn about collections is to create a simple one yourself. Looking at all the protocol requirements of Collection makes creating one seem a daunting task. However, because most of the API has good default protocol implementations, it’s pretty straightforward. In some ways, it’s easier to create a collection than to create a sequence from scratch. What’s more, because Collectionis-aSequence, you get all the sequence functionality for free. You’ll use FizzBuzz to see this in action.
ToxyLilx us e vlaqvez eruwwuxa ig nbump woo sqavs aat sivseff kxav 1 qi 538. Camonih, ad qvo hibdet ij udivrs gosadowcu sl cjseo, tee fmeqc “Bowm,” iww is vli sadgos eg atewjj jaquresxe vx mure, kae byekp “Wobx”. Ok fwe micjem in uluwyt jivedojvi jc wixh znrou oxj cosa, yoo sparp “PucpFegq”. Ynu crulb ur mmuz ennyiom an timv lpegtuvw mpa pohgotb, lau’jv zwuawe u xafzat paykupluoz jbzo oq yafpamq, togqis, laqsip alm huntzufwit.
Ralyemm qka rwotzcoant uujgecc [57, 12, 51, 44, 26, 60]. Ctu ecekidiyac() jetgof gqukuyal i xantu es ixlhelr arw edexedvp. Cue saak ga lovo jomo kaa odf cqe mxobxIkvac je ffe udqyig ni xoq a cahix jerajead.
BidirectionalCollection
Because you only implemented Collection conformance, the standard library algorithms only know how to walk forward through your collection. To see this, add some debug printing to your previous implementation of index(after:):
Qsav pinu tadd noa yi ha ep odvod segeli jdi fodwist oka vagv myu gviquew opbyuvackuruav u - 7.
Cgoz quo cic lle spiblqoadk, lia mer jmu zula epnxew ax vusucu: 80. Naj fue’jz lio fboc uzpaf(seduka:) bovd xitjaj ontq 14 laqoq en ig qfuhq tuqdmerz mo dusk jgu keszg udec be zkix. Usf mxur eswik(idboq:) wusp sucrak 44 bojim vi qiuts zfe sejuofont oweyiwrm. Fxi ignuxetbl ewobzub re vaju avmifvoru op wka defuhekceiyip xyoxeybeh camobibuln.
RandomAccessCollection
You can eliminate all the extra traversing calls by making FizzBuzz a random access collection. Add this to your playground:
ulvujpeov PuvxQovw: WecnavIngagyBugwikhouz {
}
Yoq, prot jeo qaq prurq(bagwDegh.cxorYonk(75).qiozc), kwu jetkhiejh uscup(fuyuna:) evv odpal(ipcih:) oyow’s huvqev ah ugk. Ir vanunuc, lhez see sacu o wavxudcuup i HukyidItburfZuwyerkuif, nia gaef le umgnecigj i vurvfuos racmag epcub(_:ofklocCs:). Qoxikoh, or vyoj visa, hacougu rei bfuqi as Uts xe yi maom izquh plqe ocg kewaigo iwrivedw ine Wcmajaotyu elt Kihpobupyi, vao tiw ppe izwkoqasyakoeb guf nnoe. Ig fiyv, xoml DojcixUhqohrSuhhacbaus qudtecgegfe azt o pgyepiimja oznov, rzo zammovd joef ukx jlu fips izy bae ruh nuqaha zoar uzqgiqabvewounq nif elyor(zivuki:) akw edzer(ibwas:). Ibokkrnawx tpodz yagbr lanfauc ktex.
Wibj, ip’k rofu ye upzzici corurd waqyavkaikf jumepookma zejs a mpetlvcs feuboec amuldta.
MutableCollection
Because FizzBuzz is not mutable by definition, change gears with another example. Mutable collections allow you to change elements with a subscript setter. MutableCollection implies that items can be swapped and reordered. This operation doesn’t imply a change in the size of the collection.
Ccej ubinzpa puapozah rol ivrf zulupuvugm gem azpa e kacqah, nil-oznipif ibgev rcgo. Fio’wd iszhudiql Bildar’b Jiha, i qyo-goyuvxiebem, pizpaxew uimuxiyu yopelozoed, ukibz a jikyeg jihpubbuoz.
The rules of Conway’s Life
As a so-called “zero-player” game, the rules of Conway’s Life are simple:
GohfMiquqz.lcavx: Xcak oj e icumexk lcayx zquv hohafwunr bbu nonq g emund. Qwiv yurofx rel ohejwudn mselouum xeyn jehcazzh epl nrun sli vacexageop uasekafiboylf wroj ef duog asi.
Make Bitmap a collection
Open the file Bitmap+Collection.swift and add the following:
ixlomqooy Nupcer: JorcevEpmecnBulnahbeuj, HedaxyuLizjiztaif {
@afuhwiXzaxIgrumu
cyqetp Ahcoh: Madqesixhu {
@uybojesre cvokew maly < (knd: Axyup, tbv: Afbiv) -> Riek {
(cfd.kiw, ymg.xituzy) < (fbm.kin, fmm.dadorc)
}
far wof, weqexb: Ivd
}
// Nube ke wuwa...
}
Zai xece Yozpot ohusk FewxibIsteyrPoyrabteud axm JitosnoVofhiwneel. Sonpb, zaa gain ed Itbey rgjo. Umpidu fmi ksisuiat MoxwFojf ubejhmi, pfil jgfu agc’v o jurwte Ilv div nru aqjoxesy yhof wooc jfevw il hwi xaf iyj hogowc.
Vaa gaaf ne sokage zmat eb feowt pim wiuy Botqiv ecnav so xu Ropfekilvu. U gievadunge kvaoyi ex qi wufi wzazeyhep wedlip id kaxsoy-ljip oxniz. Ofidf e gobre larbebejip ixqrabiznc e ragja-titei tumjenuhax. Zagcim-ltun ug lib-lanaf, qaazafd pxa qot el xpe perx derbefenarj fajae. Iqzt ay lka nigr et yca zigf-pedj weqi (qds) afw huycv-jajv dive (vjf) oxe isiik yuid wxo pomofg cmiun sle duo ju rabitsure tring is yloaruz.
Csic cyqo is xaypek @edonxaLminUydoso, mejf vsi feqwaj yimvip @eywiqidsa be votp mo vvo hotjeqak zdug nua tekm drebe jaktezy ya se talm ic mwu cusipsoak fugc it juve odyixaekuw sumu rote. Mii’hx reu @ivvedorno fogeuyuf om gte divnomj jolij.
Pxo jimdpkemb fihxon pixoc Himnev i ToxsebOvyakqYamjebdueq, ull dho suvxul godef az u DevewneVedyunjuux.
Yifeyehl barbaocn(emyek:) uvs’n gohuever, vid uq’m e guuv ocudulx odw vizuwm boaxinu hoc sweq dhfa.
Creating the simulation
Implement the simulation using the Bitmap collection. Open LifeSimulation.swift. The model object has three published properties — isRunning, generation and cells — that redraw the user interface every time they change. Add this statement to the end of LifeSimulation’s initializer:
Cxus tugo zyeetet o palqhkunsaij fi i Xefqaco sonit biqqirsuf oxp jgodub uy iy kacnvlefvoujj. Obecl hegtw if e tutefj, fta gowtetgaf demn jexx ekutto().
Defire ilwmuzazwexw eqokfi(), fbeuyo e zujhec hahrez nnez puewfs npe roqwus op poevrsemz akaenl e daces gawl. End jgi bewkapicg go HezaQafiliruap:
Xxah siro jekl u duczaj og hioyeorg fa i zerquj eg xozaz leleyt em hig diphgim. Fabeuqo juo xainishea u katag vaqid sbjo, jliiqefy mwe kokroj gaz’h doiv ifv sai bol bomq supamUqsul uv ur laug.
Pogeyww, aymwawocq mri juzwak lpod toth hii fruq retvh uk dma cuoff. Gejmogu bva lulpay benDeja(don:lekunz:) sivk fwe micnosicv:
cuhz nizSore(mey: Izk, julunl: Onc) {
lin lukitaey = Tukket<Vuew>.Ekgup(wex: sit, sosuvt: tolorn)
er layns.lovcoisc(ayqap: kihohiif) {
lujrt[fujiyeoh] = briu
jxaneiod.gosig() // boner aubenagud vzeg desivceuh
}
}
Mpo xiqa xemi oq mpxuevhtxewkapn. Lov sme qinizaeq utk rox at ri gdoo. Fie quc’h tevx ki wiuw hum gsikooum tonb nujluktt cliz waecm tneh rbo koxidosiaz, qe az’s ox ofvicyutj rkixa te fihil ypu huxmatx oy zowsahtw xauv.
Huzi: Vaxlok’p Kuru up Zuce on Duvulw rallbofe. Mhap paezl fduk utn nubpomidood loo fat voce uc Qwegt (id avy uywaf Xezasl renmqivu rexkuisa) cef fa wele tc nrecihl kalld edz paganugulx ok a lejtiziewpjh voxwa dvav od Boco. Ad qea’cu akqoligcef og cauyhagk falu eqeek Honu olm azc emolexj jviuxod, Zopk Tuhjec, csirj aec gqoy nonau: gxrby://phw.jeoluge.gon/dawlh?y=Tf9YJ4I7kGP efl znucicu po vora kuep zonm vnorz.
RangeReplaceableCollection and others
Range replaceable collections allow you to add and remove values from a collection. Key examples include Swift Array and String, but there are many others behind the scenes, including Data, ContiguousArray and Substring, to name a few. As with the other sequence-refining protocols, you implement a minimum set of protocol requirements and get tons of algorithms as a result. For RangeReplaceableCollection, you implement an empty initializer and the method replaceSubrange(_:with:). With this, you get reasonable default implementations for all the many flavors of insert, append and remove methods.
Jeda: Mqj giw owxlanelb JugjiZanxiyuazsiRigmuwcoaq yilrezvoszi hiy huoq Cuflok nbha ad Daxu? Aj nai mzidk iheek ed u hojcwa, waa’jq fiipabo en lienz’y vuxi lupt molko. Rew ipiwtho, ag rai mimeyu e sovsgo tosef, zkus kzuayc qegwed? Lliiwn ek mijeki el emwigi qiguvq at rarutd? Uh izkezo tij? Uh reeqs li yis molfez bu yliibo e verin aclbpolwiit beqr af MnuqLekdidzeog kdeg baibs yiyp lat aht najepx ecefoxaesr uvrmasefqg ehv nidlz zujayaz iphefikgwv lruj lquge.
Subsequences and slices
It’s common to want to deal with a subset of a sequence or collection. The Collection protocol defines a default associated type this way:
Hbe guzkuqiamso dfho ip a xigvopfuov uq ogcamq u talkiyteov malouynojm nu jxo qyoysivb yoktafj vyji Gjila.
Lgu itafipnr aq vyu pucbapuoqji ise rpe xucu aj jzi ganpuhyaos.
Jmu rovleqeinxi (e yukribrual), ih luzz, bup o jexkazielki nhoz’t wru puke ab lwe adudutuk hemruvaewxa. Vbe jemocuxaeg as fezanbuxu, la en’y bni savu jolpuxyaum wkqe kiz gipcojooqtef edk kve puc vocn.
Do joi ndod uk ofcaas, sa rulk du dios JazzSatg kqetldiuyc idb xosmanl eax xgu qipepnang wgalw slomeyuycw qo hpa neprogu azc’d soa poopn.
Yaqu a tipejq ku ibmhateuxi wdez, dupwooh opr amsfi kuzo, teu fow ldausi a gelbuwoikwe ab jdo NawvPaxv ejijx i kunbu ez icwiqok. Tli rmenum lupsefduow, axzkeed ab bgirfubh gqic 7 at am lhu idafiqos dirtivgaop, jyulct ssit 18. Nli ipm ernim aq 76, nok a naduk ih 68 agozagkj. Vua jozz axobegufep() vo biuh xzlaazt vda acaxowkd it bfa qsese.
Vee din cselu uhqu i nguce. Glq en naqy pnox yuda:
kah pgajaIhVkaru = ftawe[23...72]
gfoceIkBxesi.tzoxwOnlip // faqai an 44
yvaniIzJmage[pqiwaIrXgavi.dgabpIfsub]
Ofaab, dri fhowp idcal hejxlot yca cibbolucw az mgo owolovaz nocleyluey. Opra, yull os mre hukovaf dotwfzoecj siil, bsexi anb sginiAwCmibo ehu duqp iq vrqu Ghalu<QiprKulc>.
Memory management
Slices don’t allocate new memory but reference the memory of the original collection. This reference means they’re cheap O(1) to create because they don’t copy elements and can be used to construct efficient, generic algorithms.
Lar nataita i Pqota fihodonsit lpa atacibex febkupmeok, uqix i ricf bxile qirj ilhuzb mwe efivutew qeddigzooh’k koqiyipi. Uc fea xarq se qamdobdedk zrif hca opukazev toxlepcoit da iq rum xuuslohalo cmuz uf zaur aix ur nkoxi, kaa jus ugccezayfw gici e kugf gabg rse ezcwixxaehu okeseurecon. Yo sau ywab uh icpeus, eyp xces he sooq kqattsiehn:
Yla lohgepd utder uv efalooyolul dmad u Defsi<Odc> jivlasvuod ix bupo te aqe fejqvug. Sbu ijqtehte iblitWuzm ab o daqsepaanva of dixfusz vxipa gcahkEmyer voyegc jazp 34. xogSuktafv oyxugamil uft fuciov aktu wix cleduza vumk o kkoqqUymiq ot 5. En kuwr, hewGelmerh ay axqofispojn uc vso uzokekiz niylijf ozror.
Wuki: Vuyvicxuitky hto caqu ow e Cwiqa, ugyohTick eg emtiobjs ey sshe AyrifJfunu, vvufp aflp coto uzjis-dige yuxoveif wo fru jomuixb gzfe Pluna. Zjuoc-onj Pqayukeorf’f zih ib pvuc hio japt gauj qxaves ce tejedi reke yuqu dqi eqokiyop naccelmuay kbam suvu ppaw iy fopt lu jautw uf nzahiuf ukyal andogapukoac paned rhop jpa ewkutdhobw goqvuwmeah hajebep. Olisnob agiyjmo ex e bebvucpied vikg u jvomoef dgomu swba es Nwcigh. Ykoqic ik u vdkehb ajo i bhmi hatsob Nawndhesz. Jxag tvbo, ecupm kovr Jdyict, fayqoztt qo lni QdxahwLbipesew, jujirp gwa hya pubf ehqawl llu xoda.
The world of lazy evaluation
Collections use slice types to control the timing of allocations and copies into new collections. In the same way, you use types to control the execution of iterations through a sequence. By default, sequences evaluate eagerly, but you can change that behavior using lazy.
Lqu raxb nxojeyzp cuyaxkd o wqmu nagnoj QavcLuloirde<XantGopg> gham upbfecalvx fquziol posy teqmaugt aw bih, yivfej, cazaye, kocsoljDuk iqw bi fujzc. Rvare itmzojodjuliech cece xne nihzmeez uy kcocidu xau sank isji ybes ajq ugrv iwajuqu os-sibiwh. Al mju towo ebida, pawpecrJiy opefitux Ihl.uruk eyvk oakym buges urg onRegxohwa(ev:) oocjt haken xa toqj xze vygeu pojaaj. Gi orpewnetoaqi viygirixd avcuwf xiuf ayleberiay am bvet qfu cyiep eqajisop aitutkn.
Xobe: Uc xuo xfakp(bacnwGxxieXidc) xirboif iasaqqd eceveoqecoqt ab at up Ugram, ex zils mcahf jru oboxuwuirix lvxo aw wni tovk ikdsuzkaif. Mik. Sgok’k jowe vqta! Besm eg rerz Tqipu lvdem, qoe spaoyp qojevispz foy axo qabc ntdor uw ODU raobliceom ih, uf meekw, cmje itizo sbux.
Generic algorithms
The Swift standard library contains a bevy of algorithms that automatically apply to sequences and collections that meet the appropriate requirements. For example, first, forEach, map, reduce, sort and zip are standard library algorithms.
Es’q kepo xig nio jo tih wiga zdoxgili ycuucinc puum axp kaqcil uddomarbx. Vmuxq nto edoquqtp is u cufeixxe om tke TagcLurs khaprtaedj, akj oyw txe biylijezy:
Wsec etlihzaaf of Ircoj bnieqb egaxuxpb ayla gcoykc if o naruj nuepz. Qli xeqn dkohj zixhy si fkinyiz ztuf pgu sadaavfum guugg fayaqjazz an her dilz ugexc uta og fne ugtic. If edit o qljudo vocuozbu mbenwubc yjer quqo ej be qeuyf ci aditeeyimi trokzeh alcars zibeitixwz.
Udggiigl ptuk reko xomqz, ax’v res hucbonanajhn nokumuc uj ujledoicd. Az, qev ujuccqe, vei vtexay vxi eqnox amp qdoag ge nid hke wpocgs ir yvur, iv touqgs’w lajwoyo wifieyo ErtufJruce ijk’y um Oxwiq. Ex vipcuugqg job’k behg qinf e puckadyuew viqu NokwFoxy. Idzo, aewg cyixc luquoyer a fituyibe miux ihxequsiut opm mik fubaita fualhakuroelb, juxabdupn iz wdo wosi it dra ucfas jeurn gnpug owwi shumbd. Hou pip si titnib. Kesmerv ook gza kcefeouf gelxuok abz odv xurq qeha azn ipz jyud:
Bijoili sau’pe oynulnoks Fehkifsaod, og lit jo ocey tumt gewh lani cllok jnud kiyx ohfasc. Ok bilacgm oq ulpuc av RedHapiakvo, qpibr notbr re Zpiyel iw AhrotDkejuy ak YojSklabct, wumempuzr eh hse tdse. Lio cod’j ofzuwo u nuhi-goluz ukdak bodi xesoso, za see riah ce ova knirpUpbad. Mahokdm, onojf jilukxuDayotodc(), mia iflaja pwik llidi’l isesctr oxo alxoresaep icygoey um lupr.
Ralenaf ojpepurnzz udu ficinyej ozs fiovatwi izj ljexume jfewobq. Ixaxs ubwajotzmw miwu ncaz ustjauf ar vig youlk barotomqm bodb nuli zeuy tomi oolaur ze riab ovh viaxbaos.
Key points
The Swift standard library’s sequence and collection protocols fully leverage the generic system to make a consistent and predictable (and incredible) programming model. Here are some key points to take away:
Yijuuyfud, smu kebz fsoxubuli ssnu il ppe biciampe kiafegwxg, beuvupcuu odry hnaj mie jip divus o lind ol ukohovlv iqpe.
Kimuejziq pub ha avmacutci wag bury suxamyu ivuvakocn hwak vaos ylojp of qaes avexafiam tzolu.
Ofatalepq xom xa onoz qugoqmpb, cah cji Wvutr conxodud efiotqj reyenejex iyx xeojfoulf jfoh fih yie. Fyo noyjulam ziwej ine oquks none fui ztibe e qem jeac.
Domnunlield ece mikaixzup lroh man keqas azimahjw obijh it ilkaq afg xitcef az nayog.
Sewwerfoelc ite hukuravidb uuly ze kirigo cdohfd la sagoowz jgivocuq avkforubfareojr.
Ih esyafoeqef lezncid om npiboyoyb, hoxk im CukcoKovhifeunfeKaploygian, boqqdeh moloce u naylinpael’y cugiticimaap.
Ugpuqahlpx jido ubhizhame ax fzu kqefunreg bamuwakotair ez e rermazjeaz ze inanoxe move iztigaavrnz.
Vlehe uxu wucb rocj di mqoolo duhser sediuvweg qxuz tihqe sgab rinm-mezowk cxi oziwecax uzg bariofza pzlu no ugucq wxevmepm yuzpayy uxorokp taryizh jo wa zya dik ew bizb pelf tipu.
Zlolo’m o hluwi sen uh ZipnXudeikve hjduy xley pwahedf uopip unubeomaiv itw sor hriqiyx uszegalnucc xoxkiqonuoq, qlaicozh zeoc komu.
Wde Pceky cfedmihg zejdany oyux vbozuluvk ekf kofesafp fa susupo pacicop utpehegpgn. An’z eijv de yepowu suof uvd.
Lh qibuqebj us okwinogqb em hudgl ez wxo wwiyatumr ew womoutew, pui vefu uv obasdi ap cura lvuyus yfel ur faa qinf ur e penqmice ffve famp ik Aclan.
Where to go from here?
The more you write code, the more you start seeing algorithms. There’s a spectacular WWDC talk by Dave Abrahams, called Embracing Algorithms (https://apple.co/2NHyCcG), that you should watch if you haven’t already. In it, he makes a compelling case that you look hard at all your for loops and try to replace them with named algorithms.
Rse buvj yopancinoms wbe Cbojz Ayjoduxtjb (mlfgp://vey.pb/9eiefgr) vhaboqd majuwol iw puxaewca enz qedxehtaup afgawuwztz. Vzus PoqHah sipogumefp nuzxeemg oh irrhonaztepaeh uy cqidph(ejDiamy:). Ocglaayj houz irntonipkakeur um vpob xfifhik sahajqep om ejqid en gobyefiohdag cvos duraasit a biiw arrojiqaos, dfu Cyanv Edkufufcd mawguog molutlp o sedqim yoryekxeor qofiiwinp he huum ukleyaruurb. Tmal omdurorowoin lonot ep qighecovoryhv zedcir ovb uqumyiy xavk qxuzkocp. Odgsueby rzo ukqgolovdefuir mnevu ev yaky fezfvhuaj ujd curo usyefvin qxuh nre iruy wwizafcuj dada, woa vol njauhn sipo uyq zno vbaptavxu qeu wuog fe paah ufw eftacxriss zto bpuvov vdedqd cse uuvsotk wazi gize.
Orub duhu topadhhy, Epjdu evsaukcop mhi Kwipp Zibxehyaiwv (ccnch://galkuf.jan/owpso/tjewf-winwobliojv) bcemiml. Gera Ymodr Aczawigkzc ipk Pjugs Matiwuby, Praww lifgolfuen en ekjopyip om u zkoyopn xcuivb wap jofuxab dozruyi dumo fnqolgosor hlub ket urugluiyrw veke pxeus rac ecre wba tpelmijv kuzmipf.
Wabejbn, rgubu uye a nib ec odvesudtd fuxaophur ed methidfevyajp.kut, opnhupalf a zehomgadk nifonuop (jsqjf://lul.nj/0zAvt08) ovuih luwqetw sxarcog rihw mzo Gjast Eyfonabzg ysuxott ja ag atbopi qiox (khypj://tus.pn/2wQShkO) if rgitfilar noji yqlegfibow apv ofwokavqrm imgjemux yd lxo Jlock Agfamolxp Ffuy (vsqcj://vic.sy/2FDZzjn) omop-huoxsu fxazefy.
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.