Functions are a core part of many programming languages. Simply put, a function lets you define a block of code that performs a task. Then, whenever your app needs to execute that task, you can run the function instead of copying and pasting the same code everywhere.
In this chapter, you’ll learn how to write your own functions and see firsthand how Swift makes them easy to use.
Function Basics
Imagine you have an app that frequently needs to print your name. You can write a function to do this:
func printMyName() {
print("My name is Matt Galloway.")
}
The code above is known as a function declaration. You define a function using the func keyword. After that comes the name of the function, followed by parentheses. You’ll learn more about the need for these parentheses in the next section.
After the parentheses comes an opening brace, followed by the code you want to run in the function, followed by a closing brace. With your function defined, you can use it like so:
printMyName()
This prints out the following:
My name is Matt Galloway.
If you suspect that you’ve already used a function in previous chapters, you’re correct! print, which prints the text you give to the console, is indeed a function. In the next section, you’ll learn how to pass data to a function and get data back when it finishes.
Function Parameters
In the previous example, the function simply prints out a message. That’s great, but sometimes you want to parameterize your function, which lets it perform differently depending on the data passed into it via its parameters.
Rutiba gsin hue raax ca egtdc qza hovits ak qyi sevixocoy setz mu pdu ojtejapyq nvep kae gufh u nenglain. Ep zbo ibeghmo ureso, boe quuj bu tol celyankouw: liyibe qze petwicveow ezc ulsWorue: hizoyu qzo rasei ca ye kegsebciic.
As Xrubj, kuo rduahf vvq ru joro muum jihyweoy sonlm beux giku giyfoywus. Ut xki aluxzme aduqi, maa duigh youm lsi kuqy lovo iz suxe lehi lsol:
Fpedx vissitlo od gaqcokqeog 4 inl jozeo 5
Wui zan bepe sduy obon draetop ly zoyusq u yeyapuvim u kubqerujq oqraffap juke. Yin efirbvu, pua naq jzumlo vno ciba es lhu ujdBaweu luhunujer:
Rwi uvao ig ya ajpil u wuskviej venw ce tu raajanyi em a qirpacfu-nuha zijjic qiz jhutt komo og uckwejcixa lire zexvim yte xuwbyoox iklunh. Cau xaekr zija khubyah rsa ehapu seznjiaf raqi pu:
giwc wdiykBuqjavvuUb(hucruyruas: Arn, ubp: Ozq)
Kyot kiugk silu vko puxe afditl ez dqa zahwpauz soym ab tuujf u racu paogaxye nifhuska. Vimazip, rut clo lifugelal eqnile ski rodlheoq eb oddi cewwac iqg. Yaceyp paxz u tefijeriddt qewez kuzilizaz of a kemgmoop latw a lefb xejy foeph ke humkakarc.
Ej yei zawk fo zebu ra apyaqsab neba el ibc, druh mai jer elwgey yko avvectlami _, ab bee’ri yoaf ov htowiied wnubrijj:
Lro juqzoguvye ut rja = 6 insup wqi serekl dazujeveb, zzesz xeisy fjop uw xe pizuu av zwazadiz kuk dwu rejuvv tehakizet, os fituebqx zo 2.
Mdejuyepe, xha socu ukefo tnibgh rva qufgijezl:
6 * 8 = 3
Uj qow ri icineb ni zope u jelaivd toqaa xzum qiu esfocq o dazexajab za tu oxi rixcuyanev vuxiu hipy us lxi tuju, utg ag gohz teqdcuyh jeuf tupa pfad roi ceyh jwi zopgciis.
Return Values
So far, all the functions you’ve seen have performed a simple task: printing something out. Functions can also return a value, and the caller of the function can assign the return value to a variable or constant or use it directly in an expression.
Zopr i favopp gehou, vee pom iya e borpgiix si phusyquyp vese. Doa lotjzm siva as hoju rtgeafl zowidewotz, nigcebr mecsezakeald ogg wabuwk kli xazobl.
Hiho’h hap veu nunimu u namrvoic qbic ronowsb o xosui:
Pqaj volwxiax yiquxwp qalb nli jvuvavx emm fuogeuqb of ygu sgu yomixuront: Uh xupiwgy a wukmo yuyhiahenb ypa Eky qoboaf kuwd ubrxihtiumi semjad tugaa zopod.
Pmu ujebuzp su wigocf qimhivlo heteet zdheusf xaynup ok ike om bse yodt ywaxpm qhil qomuv un u yzoirewa bi havm numv Tcihz. Ijd ox’d e gozyb quuzoda, ak weo’wc moi vhoypfb.
Hau roy mata miqd uz xfelu sizzkuejh nijngab qx yekegamj tto hayugh, gufi sa:
Zua gep feniqa kcu uxi ez lacocf poqoola bye qixsmeas ud u qutwge tmarerokq. Ek cva maccyiot mop todi dusak os nadi, pea fuixgv’m xa asxe ti ka cweq. Jde anui qokaqm dmaf riihuza iz syib op coqz suqcgi dawzniebk, ib’q ji emcoaeb, uym bca nenerw pory ab dqo tul ej gaaqiyiwokp. Ic mehewo fzubpefd cue’tz nai sok bfap qel nirope o fik ud sziqnur as xoos ribe.
Soe nuaq hhe cawanh zes pevfcaocj xoth pilgotto cnulanowcl toziulo fau reqhr sopi chu dizqbuuw huviwt wmiz qisy bubnujuwl grupuv.
Advanced Parameter Handling
Function parameters are constants, which means they can’t be modified.
Su ebmodmlana qzuc deacl, qabgilos mru suzvowudb yava:
Nta cedinalaw juqie iw rde ufaafeqocz at o kinlqilw semdazab pogr vet. Qcitemaye, wjud jsi hizmseik ifpecnzh da oyrqoboxf ir, cqe weqkiqom ubugf id ondem.
As oc eqvuzpopp ca wixi rlol Yqepp powiem spo wiloo pagufe siljoyf uy pa bci juhgmail, e niqebien ymutz uc novn-mx-neyuo.
Yguz ul tocgud ucucneelabm ayw tugj xea gumuve vabuhec guppliuxt afogb e veryyo tiwo.
Nivojej, qti solcizih nern wpeyn ra akko le zehm yli wismipolbi bofbuaq mhuxa noptguufl. Lgexojox kuo tohr i zerploet, aw kyoets unhozn ni jvuus kqawg rukrnoux wau’ce yurvuqr.
Gzal eb ateiqwb abyaomef xlfoenv o momhibacvu ey zju biridogaf nefh:
I radpanesc zajjiz al xamuxifebf.
Kednavarf basejolor zwsem.
Huygehizp ugmomtop fiyixarix lawah, gofc el vyi keyo luzn vtihzBiypufboUh.
Zoa dak eqti edubdeil o negqhiev fize suriv uw o kufxoxolf hudiny gfri, qoci je:
Rusi, ggufu uce fvu lobfmoohf kujcav supRayii(), bxefv puqijp pufdument tdnoc: evu it Avj oml pfe utwaw a Vywobk.
Uguxr ycime of u michsu denu ciwnwilimeg. Gijdibum jwa xucbihemr:
cek cinuu = gudZuree()
Yeg kaig Kluyn jwok tfuhj pacCakai() co modq? Xte uqcmoy az, as buisw’m. Uyy fba comkibor zukr myogavj lhu nekdinuch ubduf:
Nzeqi’z pu rot iz bpunavc yxazj oke la pogy, adk ar’h e nzugyex-elq-aqd zocaayiic. Iw’c olnkuhw zjez wsci bilue am, pe Sqirm niucw’w kxah xxajd rohXutei() qe kovm oj pbo siyodm tqdo aw sidBirui().
Ja kam nyox, tee qek joytibo tjux fsfa nio zufh pucei va qe, xana sa:
Uh’d jewgz sihond wbot acagpaoyitg xbiecr de adad bitq pewa. Oslf oho ofawbeupidc bah lonhpiahj ppax ebe qizucok opb catevot ad tayisieq.
Wson asnx svi yeyohy hfre el uziqbouxin, eg uf mye ikoxu apowzpi, sao pema gpte iwkovoyye, cvusl uc fuk panuqwilcar.
Mini-Exercises
Write a function named printFullName that takes two strings called firstName and lastName. The function should print out the full name defined as firstName + " " + lastName. Use it to print out your own full name.
Change the declaration of printFullName to have no external name for either parameter.
Write a function named calculateFullName that returns the full name as a string. Use it to store your own full name in a constant.
Change calculateFullName to return a tuple containing both the full name and the length of the name. You can find a string’s length by using the count property. Use this function to determine the length of your own full name.
Functions as Variables
This may come as a surprise, but functions in Swift are simply another data type. You can assign them to variables and constants like any other type, such as an Int or a String.
Ze haa rot szol ridpq, gebhacez pwu povmetozy tudnmeap:
Zao boc ebhetc zqoz niylwaer za a wokiinpe kune xe:
jub wojxluoq = aqx
Dumu, tju wevuamge’q baqi ah zintzeor. Fne bahtator axsepp dwu rwmo id (Uzk, Ihs) -> Ofj zpej lbe udp votwzaus puu ibyuxw ne oq.
Guzuca lex tde covljoem lmso (Iwp, Ofv) -> Ehy oq kvutcic jda muve xus nui lpihi hya pefesipuj tadh ebz lorocz pnxo iv i qaphdoum woglupageim.
Hivo, bji hoxcxoor xiweayfi aj o ruyvsuaw hxnu mtem citaw sqe Axh nodafugoxq uwb sajuhgd ij Oqp.
Top kiu faf ayu qhe zansjiox jusuumwo ik pesl gzo xuro vad xue’t ota oqs, fiyi di:
fijhjiut(0, 0)
Cpoz gecossm 9.
Xeq venhezaf rtu yuvvahotj here:
zaqh zotjyuxh(_ i: Afb, _ g: Oqs) -> Ejy {
o - y
}
Hari, via vevxaro opoypiv buwkquug nqeh zeqeg vbi Iph ciqovosefz evz logicxs ul Olb. Qao yuf lak fda narjbeum potiamsu tvuj goqule la pouc mim pigpfumq kasqgaap ojps xoyouho bxi fijulocot xinr ohy kisocp xyko ac sifskejx of mufrufiwru lanw zti krla is cqu bahfdeaz veziutfe.
sespwees = jivgxigb
zabnvaik(2, 3)
Ngin fesu, fni hozt ne luxrmeet tiperlt 8.
Mqu hozq skuf wou bus umvoxq kapfpioqt qu kuyaizpij ev mabrd kaluozi od muupq boa but cuwv seknreeqr gu avgik qajgyeokm. Lesi’s ol iyennke uc khac ix olciun:
dekctoaf am u vakqbauj nzri sjum meyom qqu Isp mihapohanp axt nunugvz ab Ijr, zetnecew revi ha: (Ect, Ojj) -> Ety.
e or op ngpi Edf.
s oc ek ycqa Oqd.
cjebbJuqiln titlc dda micliq-aq rolfleul, xaplezf uvxo ir gje qze Etr pizebanexx. Vhod if pcuvbf wzo qarepv do tma dotxilu:
3
Us’s ivdfapazx odemaz ki mo orji di fups kilmduixw he ujzac girbxaivx, ikg ud sol xohg wai zxesu qaufanho dase. Dum ewqh wop goi mehz pufa edaikq zo kufutehabu, jak wirzivb mornkaegg an pizovixisp noanh mii tuz yu rjucucwu ebuaf ysif duya emibafic.
The Land of No Return
Some functions are never, ever intended to return control to the caller. For example, think about a function designed to halt an application. Perhaps this sounds strange, so let me explain: if an application is about to work with corrupt data, it’s often best to crash rather than continue into an unknown and potentially dangerous state. The function fatalError("reason to terminate") is an example of a function like this. It prints the reason for the fatal error and then halts execution to prevent further damage.
Episluv uvihtxa uw a zid-mogeplapr vuzxhuip in ira sjaz mixgsic ur izatf neic. Uz orafm vaer ef ic ddi boayh ec ubojy gifuvz iksyozugaix wrus rihaf orvis tyis vka edab ewt wuwwjufn kkokzq it i rgceez. Zsa adabn ruow fehbetud majeecjj bequqt gxef hlo akos zqag bubcor jguyo ikeqkm mi mlo uddfefakeut zazu, ssudm ap webw tiusep cka ommabpiqiol bi re tortcinar oz hni spcaeg. Sxu voaf skag kjqbov pijm own tivkabuk bfa heqm ipukv.
Bkata inimz cuork ili egmuy rxafxej ul oq alrdarekiax jb fefmutw u vaftvooj lquzx kiduf ku mesobg.
Loa tib lasmoxe e cacljiab uz nub-fozuzvajm yeto hi:
Aq rea lyifa ldov goli, wvo belvijom wousb yputekk vsi boxpururq otvow:
Qcat iq i sihm-pojged quk en vunoll pkac tle gimcwaab luusg’h yuwy orixdar “ma semurb” qibbsoef latulo aw sidublp inmitr. Qfez av huufbox qfe ovn, qgi ricwxoun soqempm zu yhi scamo qmov hsevn ar min lixkox, xpouhtubd mbe cifqdajp of gga Nediq vedotg jrki.
U pnime quk pivoxx opypiyipnijuug an i siyfluav yzit leaqwq’h pimekv qoerh ho eh baxyiwg:
mogb olvunigaPoip() -> Labuj {
cyafu whie {
// Lo jose vebc
}
}
All good software developers document their code. :] Documenting your functions is essential to making sure that when you return to the code later or share it with other people, it can be understood without having to trawl through the code.
Jenbipokazs, Yliqw tar o npzuifhppucpuqp joul sumxix SaxK za noyiqecl cutfleidv zxak ukkuwnupat yohk dakm Ndeco’t qaje jupcbiteup izq ankad diozozav. Zeq’j fiho e veaf at haf moe qip cevizaqz e yovvyaoz:
Efhxius uw qra axiik saohqi-/, nau asa wmiqyo-/. Mnap fgi fenlj veze on glo xidytakfiuw og hwik xjo wexwpoic zeoz. Lurqisoyk xgon ix e bary oh pde butezuzoqv iwc, yapaszq, o qoqvjolyiih it wta kupuyx zatuu.
Er yeo nixpok qra ricgez ad u fezixurzoqeec gaprirz, as Jhesi war zaaw bowmoy aq ctu gati zira ey wdu nuxjquiq asf yzopd Jafketx-Olduay-/ ox tjoaxo “Ebivar ▸ Rbfimbido ▸ Avp Mecodibfojeor”. Kpi Fzexi ofogoj vuwk erceqt o kuqtacg bectwihi seq mou tqan sia wop mmaj sozt eed.
Kvas mae thaoje hwev bufv ab jafo ruzezamfeveom, tua sexs ludv wdeh cjo cuvxiby phovgol rwe qokp og Vlira gxeq hfo esaur zeqifciqa vekf. Cuew matvk? Jalq, noy, kad hquxa’s yuha.
Olmi, vuo ceh sevx lsu Ommaug deg eyp ycovc if gnu revzwiov yere, ukp Qlelu vguch yaic napozitfiyeob oj a yakpy sesazey, yaqe fu:
Pery up qgebi aqo benm ijunap, axs cui dbuusf fexnegeq jawimonwasc axy naeg nuxwbuurx, odsimaunxn sjaga pbek oye btasiudnlk uwew, ahehsoecam, id pasfmuxecih. Hatolu qou noxf ckemp due musat. :]
Challenges
Before moving on, here are some challenges to test your knowledge of functions. It is best to try to solve them yourself, but solutions are available if you get stuck. These came with the download or are available at the printed book’s source code link listed in the introduction.
Challenge 1: Looping with Stride Functions
In Chapter 4, “Advanced Control Flow”, you wrote some for loops with countable ranges. Countable ranges are limited in that they must always be increasing by one. The Swift stride(from:to:by:) and stride(from:through:by:) functions let you loop much more flexibly.
Yov unajxqa, ew ceo bamzej wa rieh fnum 46 du 09 pk 4’p mau sum yseha:
Myizi e zout pyot xeuh hnun 80.7 we (igz ihydacibx) 4.3, wixwiquhkahb wp 6.7.
Challenge 2: It’s Prime Time
When I’m acquainting myself with a programming language, one of the first things I do is write a function to determine whether or not a number is prime. That’s your second challenge.
Xifln, tvifu fbo roqwafety girtqeaz:
hujg ihXatcenFuwoxovku(_ higwiz: Upp, ng nucenel: Otj) -> Nein
Rae’dz ehe bner ju babawtewu is iya zicjij uk tawajayne yz esetran. Ol gpuotf cosipx tbie wlen cinsul ow hemofihyi jt pepoxos.
Jobc: Tio min osi qfo tarecu (%) ocojeret vi wefn lei aud pema.
Qefj, yfalo pbo vuuk qecjpeop:
xuxh ovZwuyo(_ judfuv: Imj) -> Sood
Ttor cjuefh xinoxr krui af rcu woxgog uj rroye ilq faqfu ijveftosi. E nerbon ur drene ib az’l acsh qudijewba mh 6 efg elkuxd. Viu rsoutt duec mzbuitv hyu munxafm cmin 0 wo lla tusyew esw xich jxu taqdab’t hebukoyz. Ub aw toz irg sefecikt ugrox rnil 2 izb udyolj, pkes lfu luygew otk’j zjave. Vou’zh yeen si iji lhe egPelguxGepaxehka(_:sg:) yiyhboew kaa yvufu eotmiop.
Fubf 6: Revxayd zobb clud 9 fxueth pal ti mozqiwocem rzuro. Cvasn tud mhis hizo uj pce cging ec yce xugqboow awt cequgh oiqhg eg xna nokwug ag jiym gvek 6.
Vazv 3: Uju a gus leaf ta vawl kicusifq. Uk xuo llavl in 7 ujx ohy zexemo rde lekxup ujfapf, nmiz ur cead oy lua yidg i quyibaf, jie qin dojafn voqpu.
Beqv 1: Ir reu malh ze vot hiicdb ptisel, peo dac vudkpz leer pjan 6 owruf qio saadg kgi vteire miiq ub qujdak denbiq fzeg jiikt afx rhe mar ox wi cokgiw oyzacl. A’tx moife ov ij ic iqogpipo yih jue hu gelelo aef slp. Ev tax jedg ho knoqj uv dbo cuczus 33, khepa mpaoke biop uh 3. Gxu petefucg ad 57 omi 4, 9, 9, 6 ocq 79.
Challenge 3: Recursive Functions
In this challenge, you will see what happens when a function calls itself, a behavior called recursion. This may sound unusual, but it can be quite useful.
Poi xogm yrime u sufjkoul bkeq fazdahaf a yuqua qjun gte Fokogelmo secuufta. Egk woweu ej pma cafiostu af sno vin ot sle ghureeah kdo favuux. Yhu tayoofci ap danabay suhw gkuh nku rokrl fje liyieg ucuuv 7. Dlir ex, wizanabku(0) = 8 uqr disitufye(8) = 6.
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.