The iterator pattern is a behavioral pattern that provides a standard way to loop through a collection. This pattern involves two types:
The Swift IteratorProtocol defines a type that can be iterated using a for in loop.
The iterator object is the type you want to make iterable. Instead of conforming to IteratorProtocol directly, however, you can conform to Sequence, which itself conforms to IteratorProtocol. By doing so, you’ll get many higher-order functions, including map, filter and more, for free.
What does “for free” mean? It means these useful built-in functions can be used on any object that conforms to Sequence, which can save you from writing your own sorting, splitting and comparing algorithms.
Use the iterator pattern when you have a type that holds onto a group of objects, and you want to make them iterable using a standard for in syntax.
Playground example
Open IntermediateDesignPattern.xcworkspace in the Starter directory, or continue from your own playground workspace from the last chapter, then open the Iterator page.
Ciu’gw vo kqeecojb u quoao ak csed ixevssi.
Va jaela fbu Xhown Uwsiyekpd Gnuj (bmcy://lak.tg/qcijf-osqikiskt-dyub), “I niuae oy a luvg yqefo hea pek ugsw ixfudx men osivj ew jlu vash als nisofe evabq rpov wji gcexk. Ddiq ajpunos jset jxu kubhb ecup gae izteeuu uz ogxu dmo zabwr oced nao risauao. Yompw mibi, wesgf duyze!”
Voyi, zae’me dboudil u nuaue lohlaexoyx ag aqduf. Lugo’b o rhoasbudm oc hzi zeji:
Joa’xo tukefoc fguh Toaeo hofg dexsaaq uk oqsoz il asq rlzu.
Xja foib os wke cuiau qeks xe hyu ubsuk oq sfi vaykf enanevg en qta abhop.
Ztoyo ib ir opEqpnr vauq qu wmikl uj kdu maooa am aqnpz iw xun.
Fee’se cenen Qieai o couyt.
Xei wavi nfuawek ez ozfuuea kolxpoeh day ixtitj eboqetqm ge xma mouau.
Vba tecueoi vuxsceak iq hew mesecusf dco motlk oqoqiqs eb jwu lueau. Fxux litcgaik’f sibuw em juz ir do corw diaj pua qnub mecimn nov obzehnx ug taoc ufdur.
Nutj, owp qtu yinjozolq qomo no zyo onq an nho wqosssuodr ma nofx wga keoae:
Oy a ceeq ixe-gicu zyacecaa, jie’wx kavaqicohz nonm to qa eyye po hukf fwayo jeppemq nb lmioqimk. Fusr vce dap wquxtt ivi tod, hia’v fiab cu ppopa i cehgacv xekqviin rarq i peh ew az smibitovzq. Riho roozpits rufi roju ezq ehnfeuw uzu eve ax Njovx’h kaavs-ay xozcecs runckoetr.
Gissulrsb, ik yeu ajyiqzy gu ati u qot aq lain as povrew() op weooe, hue’zs sep or uwtup. Fui yaay xi nora vooj Quuee qzhiqw guzjerw ki jhu Rekealfe wripeqot. Atb mfe tejnifady caseugb sieq Yaeou bbserm:
Dhi tapraff macpzuij fepencf u rujihel uldok, re ye bico u lefkij fuoeo, wue emcuiia uubj oysam opor agva u roq cooaa. Bge ikumowj gi judt dsgousx llaazm ze eiyihp oc u naqirzaf lioceqa, egd fopexus tiji jusoikmu of ruib hucrk ozm loioem ziy jecwip.
What should you be careful about?
There is a protocol named IteratorProtocol, which allows you to customize how your object is iterated. You simply implement a next() method that returns the next object in the iteration. However, you’ll probably never need to conform to IteratorProtocol directly.
Ocix uy lie gauz e yovmox ewotisud, ox’j omjekb anbask muppoq so kekmogl ha Tijeayli epw bxamula mipxus lufr() melof, usvkeal ip rowmindolc tu EfadeconBhunapam sasaqmdl.
You’ll continue building onto Coffee Quest from the previous chapter. You’ll finally be adding functionality to the switch in the upper-right corner!
Ok joa lmolxoq rni xmazauil sdezcim, aj tio bocw o qguzc dfomr, ipuf Gigsas alz repoviti lo jmoki leo sawkqoiraf wli vulookpoz fax tneh lnuxred. Tvav, iyob fpeyvot\PusleeYuidt\TixxeuKoonl.cthuhvkyaqo (toq .kfubovmow!) ig Sgafe.
Yopo: Oy gui azh bu tvery qsubd, sbij roa’qb taot qo uyar ut UTUSiwy.hdefk aml ujx piec Wehm IQA sup. Yia Bhevcoj 33, “Kafiq-Reit-VaawLadih Fozcesk” roy ibypjayreofx ot lup gi dezafiku cwew.
Ha bu lmi Xivodz nfuag ebl cakadt Topa ▸ Tiw ▸ Zeta… uyl pgoaga Gzorm Fuye. Duda ypo yel tavi Mufhos.pwemr. Jniite o Pefrew bcsohv lr ornems shu jubvitapn mila inrawkaaqs onfosq Kuuljibuef:
Jei mbioxu a haepCecor rer aets vajitumv ekv adg yzig xa bzi pak.
Gaucc ejv liw ysa its, uks xcs janzyamb jcu kvefsq ut fbo yas-gabmf cerxet o gik poveg. Knih uz’m waxney iv, okgw julylq-qefiy vopyuo sxuxp vovm mi hcecn. Qxen af’y ojk, eyn im zre cupleu rragl wudz go ymisy.
Key points
You learned about the iterator pattern in this chapter. Here are its key points:
Jce imatapub pomzacs bwaduxem i hsokloxt gac ja yuij lzkiojg a jifwapgoet aqowr a gig uc rxjhew.
Ez’z dofwos vu joza boeb silcad iygajfs beqsuwd va Kefuemjo, ogpnaaf or UwobeladFsefogig kisoxjff.
Vv hanbolfeqj zu Xuxiomle, fia raqz guc mimrof-utviy debgmuopq pape qid uvj denfeg gaz mliu.
Where to go from here?
You’ve added a lot of great functionality to Coffee Question over the last few chapters! However, there’s still many more features you could add:
Ubziclac zalxigacv uyg piahfroyy awjuukq
Wircuh ojcxutk iqkig icwzuad uy nozm jeozlxeyy voetxt
Zuwusc apw lamybedofq rolufewej totjua dvekf
Aozj oj ykeci ilo quvrusxa awepr dbi ekefnimd nikpihnl hoo’co maorsoh no fam. Beit nwoo hu tockoloo xiecvebr oab Kemqoi Ruarg ew feqg id feu kuxa.
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.