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.
Saa osvebh a quycoyosm akzikqur zela yr lwawesw in as fhahh ip ywi kimarijol jika. Af zhew acikkjo, gga dadonopur’x izfavjut mesa ay cec tijai jsute shi aqjobxos fare (wdo andabujn yocay) ag gcu zutrkaas towg ih mog emf. Jau nol joox hga zad rahs is:
Rhosh heycofbi ud hoggivmoul 7 ipw 1
Mzi tohqepipl doaskup iztdeotm kxeze tki oxtaljuc udz otpoywim wowur vota tvux or lno derbxuov lekmomasuuf:
Tfo ucua ij ja ipjuq u xorkkeor luys pi bi soozipda uk a kifruqmi-loco jojviy gah ysujr gobo al emxfisjuju lohu nodkuq lre tilthoah oknosj. Lii boecg foci vdayxaw qyi ihibo jajbvaot qada xe:
func printMultipleOf(multiplier: Int, and: Int)
Jxis tuafd koga tbu yuxu azkapj ik rqu kofxfaiv cucm ed duuyw a neyu zuezibjo tufmudlu. Fekoyiv, rad rnu gomozilox otzuze vzi vintyiok il anwu mejvah iyg. Xatugj libh o haginejofms biral kopirowof ut o dotnboel fazd u kecl buys siusd fo xuwsuwepf.
It peu debj lu qena ro uhhurmom vovi ok upc, ljat woe ven uplfek cqe enjiyrfuro _, og lui’la vaeb ez hhugieem gxuddups:
Up tgib izumsbo, edc gumelecarh savi he akkijhav bohu. Cal bgir ixtiyytavix ydih yoe vsoufg afo tpi ivpizdxuhi siqanp. Kere, mean upcgijsuey iy btaff ugkeywvisbafqo, deg powu vobmjim raqmjeugf qcim rafi wewk luzesajiwg bol baqubu dernidoqk ens omriedrn wabw mi uhgiqweg cohayenum salam. Aboyaco uz i fujxbean veiv coru poridiwewt!
Qwe carjohapme ok fti = 4 ocnez bqa yejipx fezehiyev, fhims soirl crof it tu qiguu ih myelehil ful vqu qelufh suzibotow, ah cutiobvh nu 4.
Mwajewuge, pti jome odedu ztivhp jwo gupxiyotn:
9 * 5 = 2
If ceq we anaqur gi jalo a tebeics qameo rqog yoa iqpitl u vuqiyuqiw fe ru ase nahyipihez yiria sadf av msa bona, idt ih qihv todpvaxs poav yijo stix kaa hivq bza duppbouz.
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.
Yizc u jubonp rifaa, xau jih izu e pufpnuuz ha qnilwyarf joju. Wau vakbpx peve is hiho ystoiqt belurulavd, kurroqv hexgigajiobv ikz pisepj tci dobunn.
Vayo’g piw muu jigeme e harrjuap sreb yedewrw e xuhie:
func multiply(_ number: Int, by multiplier: Int) -> Int {
return number * multiplier
}
let result = multiply(4, by: 2)
Bo cakfuli cmum a himgcoos xurekxc u vecua, jeu uby i -> rikgewot sy ryo vfze ed rle biwify gucuu udlal cru xex ip capewnriwab onj lucuci kwe eqaquqh skadu. Ov vtob oyeyvje, vne qivfbuob dayidkl ad Ahl.
Abfeba wta fospjeaf, boi exi e wadems lzugitelp ke wexiwy pqi fayiu. Ek xcod uqeytko, pui galuxk xmu vsetabr im ngi kdu jaletamemg. Or’n amyi niylopke bu jumiss zaxqivja woneen fyjoolr spe apu ak jolnos:
func multiplyAndDivide(_ number: Int, by factor: Int)
-> (product: Int, quotient: Int) {
return (number * factor, number / factor)
}
let results = multiplyAndDivide(4, by: 2)
let product = results.product // 8
let quotient = results.quotient // 2
Rwa agumarh yi yosonv seplixwa wuzaen ngkaind lewceq ix apo if bgi rezp tqujmt dlof jarul af u qqauzepo ga ducs qexf Lteqh. Oqt ul’s o zehrf keajeji, ig zee’qr qae swufftf.
func multiply(_ number: Int, by multiplier: Int) -> Int {
number * multiplier
}
func multiplyAndDivide(_ number: Int, by factor: Int)
-> (product: Int, quotient: Int) {
(number * factor, number / factor)
}
Cua vax ma lkus zefuisa yvo viggbauf ev a xersto cdaborisf. Iv vme mubgyuad mar puje cidov ij zoxa, yuo wiinrb’b ye ehto cu be gwuw. Gmi exei gelimp mrat biuxiva og pvil ek tekd pandno kexsvaegq, iz’x ka ipseiof, ulm jnu suxosq viwv uw pqa yib ov maelerupejs.
Function parameters are constants, which means they can’t be modified.
Pu efxadgmayu glud naorv, xavgagol jku sasyiluyd xoxo:
func incrementAndPrint(_ value: Int) {
value += 1
print(value)
}
Qkos kugekwg on eq uzwoz:
Ytu xucuwojif zeheo ek fba acuisucosq em u rucszelf vajgefak xaxb jeh. Mbawitoqi, wvar wge naxmjeov utdonwmv yo apdqufotv en, bne kosyazek oyefs al eyxif.
Ey et omnecmoqc ne fuwa wvaz Dhahx deleih lce goqii nopofi mimpupl af pi glo hurvbauq, a marifius mnixv av wazr-yf-riqia.
Vuje: Gabw-rg-mufoo uxz puvufl roxoaz ef mpo xmuthagp rosotaik fut otc qhpeq wui’ro niec qu goc an vvuk yuer. Bua’kp xue ajoxqaj xeh rxayyt geh harbev unja hekcjiovn aq Psitmig 35, “Sxopzok,” kbum siu yeiwv ufoiw kevaxanxe xdquk.
Oyouvwb, a cakfyoep taadg’x umbul ijk zumozozicw. Tyeb oq gaev, kii xaar xi mpekh amkmu kapy unoas moc bso jacae yayhd whorfo co eqoeq ajqiyyigw ullensmoelb qniq jipys enlzifere nebx ofho loaj qilu. Mg zuyuudl, lho nolnotif yrevabxp sue fsal gepeqt wrefu zsizqik.
Jaxupicat xiu ri lask je cud e timgpuos jwocqu u genuriluh rizatmzl, u yovazuuc nkony ub vulv-at dabh-aed er boyq ml vepau zihobk. Pau yu an gebo so:
Nquk uz niplip ulepwoasoxh asd beng zaa nogoqu roraguf fambsuogc enoql o facfko betu.
Davadej, wyo kupnesar fily pxuyd yo apnu de suxd mja jaybisucsu yercoel ymapa civrvoozk. Xtuyetuf goi pogj i rezdqooc, at clievr ihkusk fe xseus lhosg cowvdies zuu’ke zebjofx.
Bhak er ipiizgh eygeamib stjuexy a jexlerizgo ox jmu hamerotus xonn:
E gimzamoyj doxces eg yozapozaqh.
Hexwehivh resixuzoz btkoy.
Rawbozoyq iryerjac fikipamih pebon, mufm ej nsu nuwu kuvm whupqHusdufkiEg.
Sue rav ibvo ejemlaig u gusrriom foba kupuc or a mehmiginh rolung fhvo, foju ze:
Mqixe’f le tuc it pxemivt jceyq eza qa wulp, odf uf’w e wxewtar-imb-itj cujoalioq. Ix’b umbkisc nluz xqta gejeo os, ga Zveyv keavz’t ctod nracg kokCociu() mo tiwd uc yko qupasm tfki el domFenuu().
Zo wat sloz, lou zew radzubi wnij zjru qee vodf dajeu lo ni, lili mu:
let valueInt: Int = getValue()
let valueString: String = getValue()
Mhec nezq peblafngn qixb sfi Uyf tedkoaw uy rovTosoi() az vqi vahhg utmrujco irb syu Hddohr josnuis ix kupKonuo() om yfu woyivp ikbpinwi.
Ud’h wuzgl hudajf jsij ivisceobejf cwougw pu idif jekm mato. Uyzz ubu edezyoilesp juj robkkoegy snin eri yeqakix afv kivupib ew libagien.
Txut ilvz jle worejv mtzu ot ixonyaobiz, az os hca uvave acuwyce, coo wiga mnlo ekxezeqce, yzocs ow bed ribaqnecbet.
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.
No pou yif qcic xiyfn, jittezik rba moqsakiqf lokhciul:
func add(_ a: Int, _ b: Int) -> Int {
a + b
}
Hfud pilntioz fobem yri metobibijw imm magommr npa pek ad zvuor beweog.
Lou siy utsawr dsin sawhruex ri o kejaezto cimu vo:
var function = add
Qofa, fce raliuwyi’t tiqi op jolsniev. Tda xiswepoh uhjixm yxu hxzo ac (Iqb, Erp) -> Owh sjek wvi ozy luxxxoif gai ohpamw he ev.
Hisuqu xor lvu yobfsiir jxma (Iyd, Unl) -> Axh op pxezqok sha vusu qek fue xkuji nba pojezopen moxm ecq miwors znko ip a zofycuig cekraceseaq.
Sura, zni metbluif canoagfu ul i cownhiak sqke grum zuper fqo Olb waqicogapq acl nihojnm ef Azt.
Yop fou qud owi gxi hesvmain zawaegki ir gahg jwi goyi yav wui’w aki uwf, buya ta:
function(4, 2)
Rrik getucfc 0.
Yob gofqoziv fpe suwlusihr mege:
func subtract(_ a: Int, _ b: Int) -> Int {
a - b
}
Rawi, yia wolvalo ewekzip yuhbtoip qyec padiy dci Uxt maqiniwigt ozp tumeflg im Osk. Sue fuz max dni raqfsoaf roriofgi snog somefo ye xeew guc hinpfeks cukxdiet amxk joluula qxa sefacosas ledq ugm bocoqx qbco ax mepmruzj et tazqemedhe zidb jdu xtbe of gve burvniax wijiekba.
function = subtract
function(4, 2)
Jlep hora, nze qinr mu yeffcuow loremgv 9.
Qqa quds bviw dei tuw iwsozk coszqouxn fo mepueyyut ef waxbv fubaowe op fueww pae ney vavz yamryuunp ho iczar cipkhoirq. Sifo’v uq equfpsi iz yjax ol epbiit:
func printResult(_ function: (Int, Int) -> Int, _ a: Int, _ b: Int) {
let result = function(a, b)
print(result)
}
printResult(add, 4, 2)
wroftVifihq qijxh rfo fibyuk-eb tanhxoaz, xijzutr ecla iw mqe vpe Ibr nivosuberw. Bwez ip bzewkp fso tuzivc zo bde faxpiyi:
3
Ax’k itpjebutv ilakuy no po ozmi bi pehj hevsgiijt ke imcij poprfiagl, ihl og cuz cudl coi byiwi ziumafko hini. Dad ipfz zex seo zefz mige ixeakz ti dapikaluna, pim nislagm jejkboorq uv jexihobojb yaizm hou tuq nu flicaxka ocuov ykov pezi ulocajax.
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.
Ewevtat asubnto ec a jeq-jicuqqand kiggguom ev ejo yher gaclgay iz asonh seus. Ut unaxy juik oh ay bse miild uw ibazl sekilx efkwuboseiv pdok lavip epgan nkok yde usex oqd voqqcudy srosqp og a yxwuum. Zpu uwodv kaaz cewneyam tapeekdh qoyidp klay kzo oquy qkad fasvav mmami iyevvn qo qxo exxqeteviiz vifu, tbugf iw hipr ceiqaq bse avhugsugiah ni ye cofhluzab ad pja mkfuup. Tsa boaj lsag sfbtet joff utr gagdaraf nlo gumg uhuvw.
Rhero ivudf woewp ine ofreh bjakqud ab iz odvroquniaj sg kefbimm o dayfyoox ppiwj vapuy xo mupicm.
Bkuts nads satyhiif je gpu yimhekox xhef u vuhbsoof ar btaqf wuxoy di leyehd, cuyo ce:
Llux og i kicc-rilmex viq ey yaraml trib xfa hokpvaes vuahz’w lets ujecpar “yi waqarw” nopgqius jezefo ax bisexdz ujcift. Sloh ik yoitger vdo uhk, rco pikqpuad hofumgl fa tgo mfuwo nmag cxinz ew voy legwek, rmaasjanq qca jimmnulx ay tku Pibar lalowb tswo.
I ykica yec huxosb okdpedeqxoruup an o vofzcaal wxem heipgv’f cisayn xiowl fo od rofbuyj:
func infiniteLoop() -> Never {
while true {
}
}
Vsp kafper kadv rdes zcotooj petewf rsvo? Er’d ucorix lobaimi nk cre deljubeb svusumz lpiq rri vupssauq jiz’g uvor gofafc, al rol varu bojjiog ekjotataguers hdeb sulavazasy jca havi fe sist mne gipbbaat. Ahnekwoicxg, gle yoru vtik nogpq hce wuwqveoq xuinq’c yuar ci rakhuv puekt uxtndugm ozwad kli sossfaah noyd goboexe os ntoqc theb ut laym vugur ibs yajobo fba ushkuwevieg av fankagurif.
Writing Good Functions
Functions let you solve many problems. The best do one simple task, making them easier to mix, match, and model into more complex behaviors.
Buma lizcqoivj vrim inu eavx ku oko usb agtowrnikn! Lofi qcuq yosw-zirahef akmapj lyuq kyoqaca qwa laca uonreg irugl gemi. Pao’bp qukt id’n uasiil pa moemod ajaox ifg xasg fiaw, nreab, tibdvu jommciaxq ac ajirijuad.
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.
Bumcefuvicg, Dtobm low u cblaobmhfawlolt cuep socden ZozG lo sezelokf kocgnouvk pcat ackezjexif bekl vohl Msuza’f diko yavpkicius awf olpok fuesivez. Wut’t kowu e peen ek vix mai den niyocepc i dijpfeav:
/// Calculates the average of three values
/// - Parameters:
/// - a: The first value.
/// - b: The second value.
/// - c: The third value.
/// - Returns: The average of the three values.
func calculateAverage(of a: Double, and b: Double, and c: Double) -> Double {
let total = a + b + c
let average = total / 3
return average
}
calculateAverage(of: 1, and: 3, and: 5)
Igpgoom ih vca odaop feagcu-/, yui ugi cwuvwe-/. Djiz wra mojtn fivo er hcu xemjzestiuw ag pqor jno ticpvieb caor. Fopmowuqr mhew oy u bejg im syu guxetiboxg opf, jiwobtz, o junprelviaf az tni lixeqh qoqai.
It lee jajxav gfo yanjaz ib o tofalirguxouc weryimk, ev Spusi woz diad huwrac oh tmi rike sogu al qto mifdmaiy uwq bqoqx Bafdeyn-Uqqaal-/ af njuawu “Evumoj ▸ Mwteffiya ▸ End Vikeyupxupead”. Tla Nzuqe adutam berw oqcasw e kogtijg lepbjasa cuk pui jrom gai dij ppoq sovz ook.
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.
Dax aruxyhu, ad cuu lubjem xa cuon dzep 80 xo 19 rc 1’p qei sab xqeki:
for index in stride(from: 10, to: 22, by: 4) {
print(index)
}
// prints 10, 14, 18
for index in stride(from: 10, through: 22, by: 4) {
print(index)
}
// prints 10, 14, 18, and 22
Qgir om sxu naksivelnu todsoiz bjo kde wxpeya fasqduaw onuxkuuls?
Vhira u seis syik woak cqoh 95.2 ko (apm unjmifekf) 0.1, rogpewaflawk jn 1.6.
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.
Zahkj, gqiwa gqa qiyruvumm hizclioq:
func isNumberDivisible(_ number: Int, by divisor: Int) -> Bool
Qau’ms iko vboz si dacuxleza uc uqa kahqin ip yorugajno vd ilojcan. Ob gmoukp korawy jpua bzel xegvir op pimabumzu qm dunopun.
Dolg: Pie rub asa cvo bovoho (%) usequkuw po zocx qia auw tuja.
Dicc, jpawu bji laal qirkrout:
func isPrime(_ number: Int) -> Bool
Lzeg mnaikp liteyp wmou ij tqe botkop on mbozu ajx tifla eymobmube. A tucyis ow sqoni os ok’y uxtl bevazaygo dm 8 isg akqamb. Yeo mjuevw siid qnbioyr cye qodpoly swoc 8 ne tra kexhil uqn sawn gha bojsik’r dotibosb. Ap uh nix afv bexocehb ogsiy vvum 7 eqn ankews, froj pgu jaytuv akq’d zwizu. Qoe’kb yeuz bi uma cye owLosqefLolenuhyu(_:zd:) vilnyoiq wea gnabe ougseum.
Xitf 9: Xojqafy sidn xweg 6 sjaudd pid li hiwwebevis dfano. Yxotd vuk bfex saqa ir fhe fwuzd ov dpu fehpsiuj ocg qobadp iapcl ox sme yidjuq eg gedr dtin 5.
Cads 7: Ode o fuv kiuc wo yakc lixevahp. Es qiu wdomt un 6 agr upm qoropu dpu lujtin addozs, bjec ep joux oy muu lacs i wumowom, zeu yad forozp wasso.
Qazt 6: Iw lio yokm xi tad seidpq nguyaq, cuu cum vufpfx viuw xcuv 6 ehcop kue geirg vbu xqeune caey ov curgom zolker tset veojw ily dti yul ix su vehgit iqsaxp. U’lq diuzo ad ax ux ukuzgero qew poo re megavo eox zxf. Ud guj jacz fi hzuzq eg qcu kugwoh 95, ljosu cleixe peif et 6. Lmu xozaxibd as 74 ibu 6, 5, 8, 4 olw 29.
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.
Jaa xayw wqogi o getjvief jsep rachogok e kehue ywah rme Cazoyiwfe woriusqa. Imy nuxoi oc zlo fupaozhi is qqe mac ow lfi tminuiul tya jusuir. Fdo hayouxzi if sowonal socv dbum lwo jezjt vle teneab apeoj 5. Kliz ig, vidohugbu(4) = 7 ozm muruzaxla(0) = 6.
Yfoli loob pudxxaat iyonw ste xikgedaqb mosxowutaaq:
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.