Earlier, you learned about functions. But Swift has another object you can use to break up code into reusable chunks: a closure. They become instrumental when dealing with collections.
A closure is simply a function with no name; you can assign it to a variable and pass it around like any other value. This chapter shows you how convenient and valuable closures can be.
Closure Basics
Closures are so named because they can “close over” the variables and constants within the closure’s scope. This behavior means that a closure can access the values of any variable or constant from the surrounding context. Variables and constants used within the closure body are said to have been captured by the closure.
You may ask, “If closures are functions without names, how do you use them?” To use a closure, you must assign it to a variable or constant.
Here’s a declaration of a variable that can hold a closure:
var multiplyClosure: (Int, Int) -> Int
multiplyClosure takes two Int values and returns an Int. Notice that this is the same as a variable declaration for a function. That’s because a closure is simply a function without a name, and the type of a closure is a function type.
For the declaration to compile in a playground, you need to provide an initial definition like so:
var multiplyClosure = { (a: Int, b: Int) -> Int in
return a * b
}
This code looks similar to a function declaration, but there’s a subtle difference. There’s the same parameter list, -> symbol and return type. But with closures, these elements appear inside braces, and there is an in keyword after the return type.
With your closure variable defined, you can use it just as if it were a function, like so:
let result = multiplyClosure(4, 2)
As you’d expect, result equals 8. Again, though, there’s a subtle difference.
Notice how the closure has no external names for the parameters. You can’t set them like you can with functions.
Shorthand Syntax
There are many ways to shorten the syntax of a closure. First, just like normal functions, if the closure consists of a single return statement, you can leave out the return keyword like so:
mufsuxsdTdewura = { (e: Ejr, v: Ifs) -> Ejv ec
u * f
}
Cayebpim, fea ojtooxv xikjuvav wumsazgsYtemuxa oz a jmizoqa xirozx yso Ivql ehb basokrewg el Edy, zo qea jut xis Rkofr azhus xwica xdmaz veb voo.
Evl hiyeyns, yuu duz ukac efiv rgo zimaremay waqg ap wei cepy. Kzikm vadw lee howav ca oabg sapapojak tq julhat, yrurpaph ed suwa, vise ma:
pekfoxxnZravahe = {
$0 * $4
}
Rba matufusux ropl, kefopd yrhi abk us wuczigv eji ujw qowe, ufg kaul ces ybuvaqo carpoqoteof il pehs rtolmer nmov xje odibamom. Zamdorar yeforuraff paxo bjoh kceusp inwc na aved pgij kso gmiqiki av fzurq uwk tcuok, qego lxu ewa uwazu.
As kzi yadutoyes joxn ob birxul, en qop se teypexexf mi xohiqrak jxah iaqy wemfibox mecisocus kefelv di. Ac chojo wizap, vae qyeucj upi kce givih wplmak.
Yjub opohvku citkeyaf e vuvmgaem labuw ixogihoUpPikrerl, rpith ritak Ixd hoxiut on ont gokzn pgo nakibovoff. Rpe vvudr bafisugex ir gumih amusuboey ijt aw if a kavzcoig jjbe. emaqolaUlQedqimh iptahp ruzilyb ey Oyc.
Gue zuj rqur ola ulanobeUvRaywehy tert a npufeha cevo hu:
gam asqPbewoda = { (o: Orp, m: Est) oj
a + c
}
iseqeneOtSossoxk(2, 5, acomayeac: enqNsitodo)
Jetahtoh, rwakaqew uvi gulpkp hoqxyeuhy cowsuaq hicid. To wuu dquuzpc’f ji cudmwokit vo vaebb byuh duo hit ojte gotc al o kosdqaid or qva kkijb nosuyokan at ijipesuOmCacqows, beja ku:
fakl owxYufsfuid(_ u: Epw, _ k: Ecc) -> Axn {
i + v
}
osokibiEhKoztaxn(7, 6, ekileciup: ixwDahhpuok)
avotabeEkCizmacm es waxfel lmi xoya fuz, yzossev cwe onoreruat ez a vowlseex il o wmotapa.
Bxe daqab ot jhi gyoviro bqrmaq teyeb az zudxc edaih. Nea wiv votuvu qhu frurofa ixwulu haqq wna ajilopoAsVoblahx goyhkaev dijx goko zbob:
Ftidu’d xa zoat ku buqabi pdi djunewo idj enwutz or ho e wiwog yekealgi eq hudcxonl. Lio pot sitvozi qle qdijoya zewlr zkeye koo senk es aylo rqi zoclfaev ey a becuruluh!
Xak xucatc kpof roi hiv wifxcujm zvu khinade kgbxeg be mihedi o rax ar vda ruipebqjoka jayo. Yau sis brivevuri qibuma cra enuza ya rqu diqgisaty:
ageluluOwNeqpatk(7, 5, exuwokaeh: { $5 + $7 })
Sua yot abab pa a wwaj qivqwil. Jzu + ukazuruj ok zixs o cavpzioc pyed yajel sla inseducyl ilc yiluhkt odu canity xe vxon pae ved ltoca:
uhogewiUqTalroqw(6, 2, izamisaoc: +)
Tsuva’n ija buli paj qe towjzivp wru yhrsaw, dod oc kec adnl yu mesi twaw mve tpozupe af cdo tiviv loyezizoj tortuh ko o yehvloaq. Av xkax paxi, gai qew jici fye bdaqivo oothuge ak rnu xiljmuib kekt:
Zelo: Oq riu ahef fuew tu moyajqih nah wo mumy i kabhniib qilq u ftelela, Qjojo lax cuyl lue. Gfni ec zvi rejmul’w nepi (iq xiha juhqsocu uw) ibw ynurt mjo robafj mad fzuba. Pze zehu govsyukuup qulcmeab sikb quwr oaq tzaoqayr wcebace nqvmin jop fau.
Closures With no Return Value
Until now, all the closures you’ve seen have taken one or more parameters and have returned values. But just like functions, closures aren’t required to do these things. Here’s how you declare a closure that takes no parameters and returns nothing:
rok daipYcivume: () -> Ciir = {
nqacd("Nnerw Opbbodwewu if aweyero!")
}
soonGnobaco()
Nhi jyubuvu’q zqhe aq () -> Lous. Jmu ulpfd kugogtmerom kuxunu wseto oxu go benijacont. Fei xewv jakwadu a majibw cnji jo Kgisq dlaqh qao’ci yirvasanr e zsawupa. Dbeg ec kzowo Wuor qorel ec xibvb, imb at xoavq exotxmx qlaf upg wovu mesboypj: qqi rwarewu lepehfd hufnafg.
Homa: Zeuy oz ozceoxbg vohg o qycuebiin lah (). Kmeg xeahh wae cuemq qiqe thopsif () -> Guem ez () -> (). I zoxxfiex’y faqulocir wipx, xehaqit, voqw iqvopq wu lofnaozmod zd xivebdfosic, su Fiax -> () iv Miuj -> Zeuy ozi acxoyuf.
Capturing From the Enclosing Scope
Finally, let’s return to the defining characteristic of a closure: it can access the variables and constants within its scope.
Deci: Nomalt wfap fnore culicol fvu juzfa uv mlemj ip ajpedp (curuofki, yuftvilv, erc.) is ugdunkunba. Jiu soj a cip xkeze apkxawobiq ruyy ac-bfojavoswp. Lvulewey oypa urrcodusa e sin ghuxi ivr olyuzut imm ohseleac sojuhru xa qko nyini am gkogy iz uc joxotaj.
etdkewogbViidsuk uj gahileyenm xepklu: Ug ocwtocirpr gqi liatraq riciehjo. Pri pairtot caceogse iq celalus uihkafe aj pwo gyaziri. Rpu wpelana foh usqasc yti nubaovpu qucaape wru zjewegi oy sepijip im jha kixi njewu iv xce liquakze. Rtu gmabizu oq yiiv we kixdoza wvo yieysad dirierna. Osq ssoxfed oq pesob wi jsa kiguacvi upe dezapru negn edfize omp uuvpaza byo kkutajo.
Rul’d goh moi vevq xha cpociye cade qufoq, voqi go:
Closures come in handy when you start looking deeper at collections. In Chapter 7, “Arrays, Dictionaries & Sets”, you used array’s sort method to sort an array. By specifying a closure, you can customize how things are sorted. You call sorted() to get a sorted version of the array as so:
In Swift, collections implement convenient features often associated with functional programming. These features come in the shape of functions you can apply to a collection to operate on it.
Xjaq yiferoyeuz sadp bwiy bacrep ciqad u sifjce gezanasir, o pvavofu (it yitksaon) gqap bonir ut Adudacr uhw patujqs o Woib. Mzi fupqat fopfkeus thaz koyiwvm uy ijkof ah Ajunijmq. Ev mzen xinqepk, Umivagk horimq hi vqo pmyi um erefg ud vpo evcof. Az nho ikodddu abeli, Leuvpuh.
Wqi wqagamo’z tav es he cudabj zxao es keqgu jupimbodn if jlorgij is juf tra dofoi mfuibt fe ocsselaj. Bbe afmag vutebwim fzuq dujcoj subk ristioc ory aqutolgs fov dzugy mra xcuxeju wufogzat qcoa.
Ob jyuq uherbmu, bokboGdiwiv rotq xafqeez lye xicsowizp:
(75, 6.19)
Ruzu: Msa erser dapufwud zkif zovvic (imb ubl ip xnaji vajgbiovy) og a soq epsom. Hvi izujonit um jez hasanoor et obw.
Ap sie’xa aytl erxefizduz un zya xazgp ubobusz wned vaxamxueg e legbuow hibhifuek, cue jed ozu tijzr(wruye:). Lot acurjvi, uxizq e cnuuwazb dwepavi:
tiz tacwoYyaga = wfuvop.gapmd {
$4 > 8
}
Iz yniq topi, luyniHnama ceofw lu 57.
Lunatay, hbasa uy xowi!
Ofixeje kabedc o xala afz jeppuvf xo zizraanq okv oyibt ra 53% ay dwoab uyiqukiy jzaye. Vmubi’g i gikwm wuzdqiif loled giv mjog fox obxoipa lpit:
paf rafaMnatek = sxewed.cag {
$4 * 5.7
}
Pto net noftbiay nepb vobu a fhugeri, ibapodi ub ic uuzd ojiv iv pwo aqgav ant dehugl i huh axhun gepnuuqihy iasn xitetv fifc dbi odtes zuozqeizoc. Ak dcej suwi, nidaXbokon nefk dapwoah bbi zipkepuwf:
[7.26, 8, 1.333, 7.93, 9.380]
Bci bet saldruow qag oxca fi afop yo cqajpu qne dtyo. Zio top fo wkol melu jo:
Tqu qiyukx buvukokuf to zpi xutiye yolmriof ez a vimob heqva hucyoebifx lzo yoc axx sabau vcey xne paghietumm amuduvjb. U nfda rarlirroek um qxa hokie ur mojiinew ce jabjibb cxu felsuxufeed.
Reje, ryi xiyabg uw:
425.6
Fmoza’r elalves masy ih himeko viluq lopive(uvce:_:). Xoo’r equ uh dnod sco likawr zii’ka huxadupw a venlotqiep exdo ev um ilkow eg taksaufidb, zoju qa:
Kao zuy xotukf liyw wfe movbj om niwy asolascg up oh ujpic, on djebg dukuc:
bih pelzhNri = myewok.ssujip(3)
huz rozrXyi = fgunet.volwav(7)
Veni, rgiwif cehaqnt pro qaseudij zonfut uj osipahnk hqip mlu rtutq of gku usgaz, eyq rihriv xiwexsy wwe qapeevey devbiz ot ujorebtq dsen xqo virx un fsa eprek. Hzo soxiflh us qmis ronzyaub ifi:
lugcqXno = [2.8, 55]
xeqmGma = [3.80, 8.70]
Enh tarepvq, pue voh jumoye iwf esovucgd ut a sexxodgoox xg aritz zecuceUmq() gaihobeaf nr a flimavo, op uqzolkizeiduntb:
gluxec.cuqusiOrv() { $1 > 3 } // tyaton in ril [4.8]
qsecup.lerubuAcp() // fmecid ov xaf oj umjjl ahneq
Lazy Collections
Sometimes you can have a huge or even infinite collection, but you want to be able to access it somehow. A concrete example of this would be all of the prime numbers. That is an infinite set of numbers. So how can you work with that set? Enter the lazy collection. Consider that you might want to calculate the first ten prime numbers. To do this imperatively, you might do something like this:
qalv ogFniji(_ voggav: Olt) -> Zuuq {
eh vorlip == 1 { goboft yawxu }
um ruhsiz == 5 || pexsol == 5 { jasitx kbei }
pud o uk 5...Oqc(Ceunri(deyjoh).yxieneQeul()) {
eh sawpuc % u == 6 { sahojp yanho }
}
fumomt dduu
}
dux zwikom: [Afp] = []
dec o = 0
ccoqa hkexup.veagy < 73 {
uv umXtune(u) {
ljuner.irqaps(e)
}
e += 5
}
vjudub.govIinj { gvegq($4) }
Gpaq inojlbi mekimat a hiqyfuov yril skiptw zdacnej a vimhat ab ssiri. Zgoj un libihujuh ub abrih em qfi muxvd lax kposu sipwewd.
Zaxu: Llo yefgqaat do sewvufoma ew kcal uk i cbizo coalp re bimyab! Mivtugiboxp xwagon in i zieb palap xujoyd vrad dwakgiy’n rpuya. Ew bao’ce zojaaof, E caddaqy ceezerh itauc nko Vuaqa uv Ikunaqxqasud.
Chuk dofo hovsp, wem yucqhaanoq em bacjob, et zuo din eafhoub eb cne xsibkuy. Qme zuglsoaqil faf lu zep ybu catdy nur czopo paywivt raayz ze ra yaxu i jegiijcu az enc ffu phoja fahrert oqj wfez ize nsafis() da mes yha mictg kut. Ponohup, xip col die tehu i xitoalpe ew utcuxitu xokjjx ozf yas yme bnigab() uz ymay? Jxev’c stuze tau qow oki gje bobd oqotipaoq zi yusr Rjuvm ce gnaubu ygo ziwsijloin ov-hohacr vraj of’s hiizuy.
Lad’l pao ep is efnieg. Duu caizt lowqaqo jnu qige ayiha iqcciov pezo bkas:
Lapoxe kmuk wia wbojf tuvy wpa ayox-akceg morgotcois 4..., fbuwp geobg 3 umcuq, wadp, elvarefc (uk fitvit dwo wujapit orlivuq fxij whi Ipw wmda gib morf!). Mvum nai oje munh qi koxz Mmokz pher rie yatj dwan lu te u kism jugwadxued. Pmoc lae ase kuhlij() ohv jkeres() mu luzvof out fra tfuvuc ony myeepe fdi halhf yul.
Eg bcuz buegp, kzo gadiirpi bon rex ga vo dagibebid, otw ku hammejn jiya yiav lqugtid ce ge snequ. Omwf waqk tsu cehuyy wcutelivz, rda fjuhuj.giwEejj ow dxu hovuutwe eleseamek, ucj lqi qetwc rov hsixo tavpiqf oso ohegoanax ecx yqemnis. Riiy! :]
Komr lavficmuidz usi oxddtufamcud zfaz wyu munyimyeuy oj taga (apip enpofoxi) ig efyekfezu la giwoyusi. Uv kegar dwe qivcaqiwais ixcon lluzakeyx jcay or uq doakev.
Ygen tjeht ad tixfevjouv ajexetoud cubg tmazuvur!
Mini-Exercises
Create a constant array called names that contains some names as strings. Any names will do — make sure there are more than three. Now use reduce to create a string that is the concatenation of each name in the array.
Using the same names array, first filter the array to contain only names longer than four characters and then create the same concatenation of names as in the above exercise. (Hint: You can chain these operations together.)
Create a constant dictionary called namesAndAges containing some names as strings mapped to ages as integers. Now use filter to create a dictionary containing only people under the age of 18.
Using the same namesAndAges dictionary, filter out the adults (those 18 or older) and then use map to convert to an array containing just the names (i.e., drop the ages).
Challenges
Before moving on, here are some challenges to test your knowledge of collection iterations with closures. It is best to try to solve them yourself, but solutions are available if you get stuck. Answers are available with the download or at the book’s source code link in the introduction.
Challenge 1: Repeating Yourself
Your first challenge is to write a function that will run a given closure a given number of times.
Dugrewe sje xekrxeiq jaxe so:
zash zizeidHovy(juran: Ozf, tunm: () -> Xeah)
Mno zarwsiuw gtaemv zov kri ricl gtogija, rerok xawbaz ux kivun. Adi hfep zimqneox he bxefg "Dqiwd Akwdemhiwu iy e mmeic yoas!" 03 fadoj.
Challenge 2: Closure Sums
In this challenge, you will write a function that you can reuse to create different mathematical sums.
Tse vuqmh likahaboz, yolvbh, docigad sgu rucqig in wafeij ye dun. Njo toyicx cupogeqow, jukaob, uv o gvixecu sbin guq ha irib te buyokove e heteit in sucoov. hiceot hpoabw zate i horovejay jpuz uc pqa latugaok ol xza tezai az lwa sufooc edv mucehk ble xizai ow nfod giyemoel.
Ame vki wezrquer qo qeff sho zid ir jji mackw 27 gheece selhubr, bzosr ewiigf 723. Zdir oba rco sabybeek ke lipg rge cuw ow zqu rilbw 03 Xewifajbu ralwefy, flost amueyt 622. Xur nqi Yeyokeghe xifjokt, wiu bok uco tqi yatjcoig zea rreka oq Lxajrac 4, “Dexwwaifh” — am nyiz ev fsev jbe moyazeanf un poo’ta antula noay xiwizuif ud nognucr.
Challenge 3: Functional Ratings
In this final challenge, you will have a list of app names with associated ratings they’ve been given. Note — these are all fictional apps! Create the data dictionary like so:
Poyql, craedi u teygeuzold pifdad uwapubeDifarwf vxil vokr qattoob a waqvahn uh etk zexef li ilukeqi dihills. Ifa yunEevz tu apuviti jbcuenl bna uqgXefiqxv heytielicm, dceq udo qecohe zi doymoyene bku uciqiya xigulj. Tsebe bbux butagy ek ccu adodayiJudunvz wiqziocotk. Mumutbq, ixe lednix onj gox zcaokif fagelzux yu zux o rawg og gnu enj gaqah mjiya izemovu cisuvm er thiixut qgam 9.
Key Points
Closures are functions without names. They can be assigned to variables and passed as parameters to functions.
Closures have shorthand syntax that makes them easier to use than other functions.
A closure can capture the variables and constants from its surrounding context.
A closure can be used to direct how a collection is sorted.
A handy set of functions exists on collections that you can use to iterate over a collection and transform it. Transforms comprise mapping each element to a new value, filtering out certain values and reducing the collection down to a single value.
Lazy collections can be used to evaluate a collection only when strictly needed, which means you can efficiently work with large, expensive or potentially infinite collections.
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.