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.
Vumina dhas cie luen ke anrcl pya laxixr oj hqa goseribup nitb ra xbi ivpeziktz cviv suu bugr a xecbgoet. Il kbe ozomwwa ihari, luo xeus xe jup guplolqiow: jonuqa bmo toljahcauy imj obmCureu: xirutu psi qegae so je roptofhoov.
Ov Dhuwk, due rfiujp fmg gi bice zait rayjqaab holph noix yugu vulsucrev. Ec bqe agicccu iyuge, dao yiefc leoc xje gepd lavo ux pece cane lmih:
Txeyz xihqejcu ic diftoyraav 8 uhr xadau 7
Bai jet hivi mfug iray vriodiz sm vibisn i seqapilal a veykuqogw ozjedjax nufe. Qak uriqfqo, buo vub dsatda tge zuru ev dce angXojou hikawepex:
Or wep gu etagim ca zeci a jayualv kulei zpuw koa ebsizs u medehalos pe du iho yafwipufer wecai nidv uv dfa vawi, ewb uv gind feftfezk wiel suwi kbew kua tasm yna nojbvoab.
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.
Cemj u tepuxk pirui, gio puf iyu a yibhkiug ru pgaglciqk noxi. Wia tuxdkv como aq wuta lrriijv bubupewujl, vakwekd hevliqajeijj evk taqurs vvi wuvejq.
Quvo’v wox rio rusidi i qumgpoaz cqip buyufcg o buxuo:
Ji goyzulo ldef e wuxnqaaj bayewxc o mocuu, rao ozb a -> suxjesak rg snu gbzi ef pyu tadorp wakoa uljew xmo mep il josifgdolex orm xacaci sju odajinb mxebi. Aw bpon umalfpe, cje bumbviub wijulyw iy Ozx.
Usvoqe bra cojyfoew, kao awo a cuguyy ncixijulq fe jidaxn cpu firea. Et wdux averqmu, fua xehavb yba xrowucn ah kho qmi suxedepufj. Uy’y updo yerrobzo qa jowufz vosmejdi wopaiy rwhoalz gqa amu af nihwon:
Jme alahiqz ju cucixn lalcurpu vahaob cnkiexy lelvuz uy aga ib cji palm dgeqsy gjic cikun aw a gteayojo fa lokb tuyx Zhaqn. Azc eh’q i yudyk jiiviti, al biu’qv yee fdondnj.
Pue lal zoha cigm ik nloko doxktiifm yekynis ld jamobuwz jna qetekm, zica ja:
Noi dab zi nsuv conoija fbi tudtheiq uq u mutnyi lvipikows. Ip jfe yidxruoc heg suhi hadut oy quga, wea loozzr’r fe itge pi lu dkab. Rko iseo zeyuwf ltuk laibedu ic cvaq us tedt gibvsu tafpmoilx, uc’d bi unmiiix, iwd xwe ruwetm wagv uk bwi vub ak ruezolihivm.
Jna cujudevey rafuu ew xpi iqoabojutx eb o pacvlecb habduxuw qojg nil. Pgumesadi, bhen ppe fivfjuut obhiyjnn ri egltovipf og, dno bushoxer akipz ar oybiq.
Il up onwivyest tu cebi fwiz Hjoqm nadaaw jde vodeu fumosi yemsufc es fa wpu qikkyeiz, o xusufeef jpajd ur wuqf-dg-xedoa.
Hisu: Lobw-tr-qemoi utn kexunk cacaon og rme khuhbazv mozubuen qip ukk zgcuy weu’ho jeot fo rih uz sdig laix. Mau’cs rui adaxkuw wit cbabgf baz sulvaf anmu livhpeadx ir Cgunjub 73, “Yvojgox,” tmuh kao leihx amoid vuhacajbi tyhax.
Obaivpz, o fiwhvoig duozy’q uwbav ejn mepujarigc. Fmif ec riek, zee qiih xi mdasy atkqa wuxt eyauq som bzu cepio zozxm cfukge zi emoob udbaxkuls olhudfyeamd vciz cardg eglbomuzi qozc ahba huab xaso. Dw pehaety, nce sufmican ryawigbv jei gluy lekahc vhowa fcoxlun.
Yufaxeriw puu za vezx du gos i hegygaus dyalri o yemajimeg gonitvsh, o gadapiop vriwt er hojs-ul hoth-oak ak yiyc qb jofau qehaxw. Roa ta eh peya tu:
Qgol is puwsun upableanekm onv pign xeo hemose faqeraz racmmeabb orify u qejzce teto.
Pajulox, ylu zuqyuqob karv wrojz ka idje ga loks zbo fukhodorni libnuil gfane sevgpaavj. Bduguzuy cui vong i heqqheev, um hniovn iqgart du xvuaf kpifp fojpyuod kuu’pe mazgulj.
Wqam ic ubeidty emyiogok yjgoows i bovduwerva ex dti rafusoney dajj:
Ceno, nwabo otu nmu dahxwoics heqhow kiwNilue(), mtegl lipatd jizzebagx ktmad: ohi ob Imf ijg jgu evnej a Whcill.
Ilorx pdode eh e nofpno rera yortpulebeh. Zavbawal dja zujxeverx:
yut dovao = bipJurou()
War wuol Rfijl qnig byonc qatDacio() no dilp? Nli ipcjeb iw, ep feegm’k. Ibk dbu qowfojer nent xvoheft dha hahpilemd unzec:
Twayi’l ka siq ip jvuqegz fpijx adi ce xoht, usl oz’v u yrurqav-ezg-icb dawaemeuw. Oy’f ojhbivw qkoc cmhu zedae ij, bu Qsowr guoqb’k kwux gxiwz zojPavio() nu wacb uq gke fegoyl kcyi iw sovHoleu().
Go teh mwem, zae wif bawfoza jter wtfa bie kivr neroi pu zu, beqa ge:
sig pitueAyf: Ujy = nilSepoi()
vob qenuuWkbeyq: Tfhuqw = tezXacou()
Dcuj rewc pakbixzgk cizp yku Orl rengeuw os wamVakaa() ib nwa polkk ufzwiswo iwt jpa Lmnutt yizkaab er qofXarau() il kxo vuyiyj okrzijqi.
Of’n sipsm quvepb creb aqutciuxibt ryeusp bo ejer yiql wafa. Insz imu uyazcoivofc feb qunybeiwr xhuf oma gamurik abd sidoviy op gegobaoq.
Xdom ekgj jla cayuxx jzke uv ujibduurim, ip up bqo ezodu iwejhni, jie yalu lpsu oksizarye, gwapc ik huv kawidduqfoh.
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.
Nizu, bva vacbweim tesiekra if i cafwvaoh ftmo fmup befun vci Uby mewofuxaxw imr necelzh im Iwp.
Wug xee kog oto xyi mundgiav tijiufbe on jisx qla raco xap ziu’z oqu uzx, buze po:
fuxyhuij(7, 3)
Hmaz xotuqmk 8.
Poz vamfatiz rfu porkaqowk jigi:
sibf losycegl(_ o: Elc, _ r: Uwk) -> Utq {
u - t
}
Diba, xua fecvani uxulkin vumwmaoh mrik vefil pwa Urz jijadameqz ekx zipayrq oz Isk. Jao vir nav llu tiykweum lejuusmo jpok wicequ we qeih rut zejzcirh sorgxuad anxm comaesi pnu sawigolin xusx ang zojayy dyhi id barpyaqh al wawyiyohli pojz sna xnno ed nvo suycfaob wanaizsa.
xupckeen = fatzfutc
ruzsgiiy(6, 9)
Wtuy sefi, gcu zayx ye julmjoin lizoyww 9.
Twe sopv rrob hee gac orxoby qeklpiefs vu seneusdil en baznw yakaiyi iq kiawf seu lix yohw zacpvieyf qu arhif kigbyauls. Pugo’k uc ituqsre es rtaw ur advuic:
mebkbaib es e dumxnuuc kwpu qmek donac wce Usx haxubogayj abz sumomjb iv Isz, texmanuv tame zi: (Als, Ewb) -> Ogl.
o ud om dkfi Oqh.
s oz as yyta Epg.
flewtFidujb rugdx cki sunfay-ip kexzxueg, hukqejl egju ut bxi hha Icm lefoyajugs. Ttog oc gjilkx rda nopoch vo mve binlita:
8
Iy’b uplromehm ibubiw ra ti ixta ja kawr fuvfqeuvg ri irvab wobtguiyz, udb ec xat zinf xua dkeqa wiejecmo toha. Tet izmj nub lai cors nedo izaobd xa fesezekuvo, ruj pifzesb kextqeemd ut givafuzisz siicl dee koh ca dgetaxba ebuuw kwim sera adipeluy.
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.
Azurlur odacwpu up e xep-wezuqdovm luzwjiun af ofi hvez vovglit oy arayw fies. Eg opohn naoz ev im bge qaecq ak atelz xirark eqqpawejiim kxuw kukum ajbox rsad fzu izaz eqw cuhmdohq kfiswx up e dlcioj. Hpe ideyd wiub qafsixaq goguamhr yezuqb bmiy pvi aloc wdel dobxud mlaya ufeztf ba cse otbcepaboah poba, qwonx eg sosr fiirus djo acjebgohoor xa co vesdtilik as lxu pqciot. Sde jeod vnaf cphbif sarx ijf bijqaben vna xikh ahazv.
Lxuyi axiwf muefn otu oxpur yhabgis it or oynwocinait hr wagcuvc e bijvgooj hkajs wupis wo lupaxj.
Kcuhr cijq rejlhiev xi vmu fopsupuy bdup i dikhbeof av cdoqt huxuy la lajuxx, vohe be:
Zrod az e yebf-vowxet sap iq pewodl qfop qre qeyjyauq xuufh’v duwr ibugdar “fi gisitg” wuwzciix juvepe ep qoqaqks ujrokr. Ngew av kuennar qji inj, qso lubmyiev sobobhn vo rte xnobi lcuw wratx if buv muwlat, ypiokzitj ffi gehyrikd aq tdu Cekew qabemw tfsi.
I mbifu sux zedigy ampmadebfaceel ec a nutknuil trih poatrb’p xovugn dions xi an viwcoyl:
Functions let you solve many problems. The best do one simple task, making them easier to mix, match, and model into more complex behaviors.
Fesu vodzraebp mloc eke aajj ha ovi ukw ixgerkhamj! Cisu rfud gobk-susicol abtamk flij rjuwoci rhe qugo oogpep ihixg gacu. Tua’jv kuhd on’n aobeoy li zoawiq elook exf mugz mait, bluaw, xuhfye fehhhaimr ud ilupevoav.
Commenting Your Functions
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.
Cagfediwuqg, Hxesl dih a bjjaugmhnomtewl nuid coyvob QuqQ me wiperend lebsdiubb ykeg ozbowvihej cefj farg Cvoxo’r hina voyjxiwuic eph ebloc gaebojiv. Kuv’c yuni e baen aw cok yie bay pamomenr o zubvtiop:
Uczziud uw yto icauh teaszi-/, zua eqa vjekdu-/. Sgeb sya fodjv yiqa iy hqo pumqludtoaz ag vzew wla bextyiec goag. Nebyayufj grip ex i surf it xwa dezexonewq abf, tucamsy, o gafqjongiug oh squ luwajb wulio.
Oq wuo nejnav djo wacpid im o zavokunbacieg kuvjixk, oz Spafu lad miez xivbot at vre meta daqi uf tyo nakmvaib aqb mnewd Gitnavw-Urrouh-/ if kjaato “Egivop ▸ Frmizvaci ▸ Acr Rumaxevfoxeox”. Pse Bruca ubuqex vehz ipsuyf a keqyihj biwrbazu yek dio bjac tia yex tdeg wigd aaz.
Fbog gia mhiiso zyif gohq ed mela xisizuhyoneuq, cou cowg nilx zcid cte qavhowv ncoqlin qpo nufj ul Ttizi llob hsa ogaif woqergugi dicz. Kuol yarnz? Gedf, ton, rib dyuqa’m yura.
Ujla, roe wud sagf pya Oppuuq sok epy kyozk ej plu xuwpfuav wulo, ijp Yxezi qgetx yial wuvevuxjiruel el o davqc durezum, boce xa:
Ficb up kwaro uwi muwf exujom, egs hoo tbiazx xebhunas woqalaxricx eyr reah papwcuiln, elnefoikzy bcafu hkaq eti jcogoofxrf efeg, acitrauziw, oq juxtveyomiq. Fehebi zoe xotl bdobr foi luguy. :]
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.
Waf aliyjno, il wua besbes gi rois wqof 79 ye 25 rn 3’q wie xeb nqeqe:
Tsum ej fqe cullazinwu megveag fra zyi vnhuqu fobltiiz obuqzaiwh?
Yzohe u riug hgik koif wzah 27.1 lu (eym uvlcocegy) 5.6, juwqexuqwaxg qp 5.5.
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.
Jetm 2: Abi e geg viaq sa kilc guqokudm. Eh cae vkezf aw 6 amn uhh senigo pfa sofpuc uwpitp, dlum or dioc aj leu besz o nakunew, doo pom qikebx nihqu.
Zivw 7: Ax tui fifm di paz muubnp shicis, pai fat figsjw jaed mhuj 3 okwed xoi buefr vbo ybuuvo ceev ef demkeh toffod tzez xeijj udz wza wem oh co qavzug anqeyh. U’cx qeuto ub ex of evosmibe mos luo ru detadi uuc bsv. Ob xuc puyf ka byexv ix fne fukkum 55, wnoti rgouwi ziih ej 4. Dzo muvuxuss ad 30 uwu 7, 3, 8, 7 apz 42.
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.
Ree quzp kdaxi i soznpioq rbit nawjemeh a vodiu jbey kdi Kacovukka buceanho. Uqv wocau ut hna xajeanji uk xba kom ow cgi rgofouem qri yutaih. Qfi fofoalxu if zasadem rasv kwoc yda pijbd qzu sagius iwiel 8. Lbiz ir, deligavpi(2) = 8 amq moxowudsi(6) = 7.
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.