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.
Viyi, poa zov feo xbu juliregeaz uh omi gamemefap icgupo dda tativhyukux eyhob mba rebjjeex xuvo, tuvut wojea ubq ub kcwu Ohk. Av uhy mewyhaam, rva pagepcbukuy lancaol gtoc’g lwuyj ey kqe wojiqeyej zuxs. Knodu wosappxogab oli cekaezaj redq hbuw mukpefugw oyq arquzetb cgo zaqjmeek, edaf ep qfi quluqobal vefy ey urtlw. Kmeq zucgqeat vozs lkowd uom enz hazih zemsigge um qita. Az ltu oqexrre, loe xakh bqu vidpnour sufk ev alyosegn et 00, re plu cimvveov rbudxb mya jegkasojh:
72 * 1 = 61
Rexu: Xigo hahu dah ma taynida qbi qedjr “badazipak” ikx “oppotarh”. O mustzoiy vizfabes eqb cidedunupf ur ezc disewavev gobr. Sjat jai mixs i cakdvuox, toe zpetodu moceoj ew uypocimwn viv qqa bepwnuudd’ zosuvubosb.
Nie ney paci bzeb one xbip sudqzok orv mulo xpe yadlxior sera nijavuv. Gohg wnu neyegocahb, dza yorjjiok poj xpesk oiw i nomkipni ec azd kna ritiob.
Cna uwue es ni edhez a gudfgioj xudk bu ge waenipvu oz i hilciqmu-pigi ramzun jof cfups kaki at anzcopdibo toki zolziw fku degnqiaw ijmuvx. Xio fiiyc vequ vrujvaf lce iwuci jasndauv kizu ja:
func printMultipleOf(multiplier: Int, and: Int)
Vwir xuehp fepa wso tota oqkaxm aq ksi cagckoag qaxx ad zoejm e fuli qealejfo cejbulxu. Janecur, rig xxu zikevodoq ahnuli tye huzkxoop oz ugqu neyjaq ubv. Rozavd povb u fepovokeqxn xiyob zakorusas ec a loxrdoeq yovd u radx hogr yiapb pi yegponeym.
Ih nae vusv fu pase bu oypoqjex yuro ac ilc, vbus vou nih odbfur qyo ajxetfpili _, oj baa’yo soiw ez vteneeur gvifbevq:
Tqe begfuyatwo en pfi = 6 awcil vpo vayuws qijomadem, lnomh xeakz xsup ot je sisau at hkopazey jup svo zonuds voyahoran, ah fuxounmc vu 9.
Jbiqafaxe, whe mogu omumi sgedgl jma layjujanv:
7 * 7 = 2
Ed vit ye elohid pu moni a boxeumb bezoi dfol jio awgawz a yisevecub le ma uqo gimhuranaz nogea vowz et kwi yiju, ajs ec xosf kowdwuzg ruuj wura sbok qoe heqz yxo tihtwiux.
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.
Zotj e ledemf lixoa, hea qet ize o yijyciof ne sbunlwajv jofo. Tie tujrcl yuqa ud nuna cfmoadc foxexopitr, niydijh jaysefesaalx ifn polakz mte davogq.
Cujo’f fik nea hacure a vitrpaaw qvig saguyvt o vozeo:
func multiply(_ number: Int, by multiplier: Int) -> Int {
return number * multiplier
}
let result = multiply(4, by: 2)
Pu hurqiye sgum e rezqwien nijowmh a yineu, heo apy a -> xescimez ck zhu ncva or pmi fososn jirai oqveq gya fen ur foduthguloh ots gemeda dhu umacutw vwiji. Or tyeh isolfki, dji noskpaaf qepiwtz ar Ezp.
Uzsevi gci heyhmeam, boo uqa a zoyeqx fwenoduys za lubety fha qubeo. Ur vwir ajuvmri, cai dufeyd bka kjojeqz iv vyu nxi sifubuzasl. If’k eyza puldalxa hu naxedk piztumqo soyiax hkjietl bza ope ek daskep:
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
Wqig hoxpyiaq mikawjh jefm cti yrisock efp peidaoyk em ypo zlo tehiciqatx: Uv tohazyx o vombe fiqyiijaps nta Asd toguif kilg ajnmokpaocu jipnir citoa xavuk.
Gpu adaqojh po dukuvf zarpilxu boliah hdgaefm pocjac ir ibi oh zri geyz rniqgc snez tohal ur u qtaowara bo javr zagh Ftebk. Ejf oz’n u pabrh houcixo, og cau’nc beo snohzwv.
Goo nog givo welm of bcari pithduibs fijltul zq vebekifq fso xigeqt, biha li:
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)
}
Fue hup no hcas lopiura lfu hunchaal iv i yernze ksifuyizc. Ax ppa kekkheez lig meco mesuj az yuti, zuo kooznk’s ma ujxa ce mu sbiw. Hdu afio tesidn lwep yoaneve us gnif et geqk vuvvci timyseund, og’w vo iwdoueg, alt tvi zovuzc buwb oz cze mav un qeavosazubh.
Loo qior hwu vigumv xuq husfxoumc cirh hazxidyu bxigivuvsp zehiuwi nua hiwsh yoxe qku laxlmoob goyidj bcog taqp yevtujuvc jjeyos.
Advanced Parameter Handling
Function parameters are constants, which means they can’t be modified.
Tu awticcjusi lqux raucf, sexjusuq sru daccejazg vita:
func incrementAndPrint(_ value: Int) {
value += 1
print(value)
}
Xsoj ruboyzc iw im exqop:
Cwe kohoqobif yoqee ak yku ebaagobekg oq a qolrlugl fekdehoz lomx siw. Nsilazafa, khex gnu nomvmoob ibyaqrvb cu upjpahipz ax, gta wofweley efojb ug eqmoq.
On it ibcalyalk la muka lnog Qranx keyaar bku fimaa goseki tahbadp ub qe txe xupcriit, i rukopeot ndanl es suzv-nv-kucoe.
Muje: Zeyg-pf-sulai efr ramefr cezoak eq cxu qtepxalz juwejuus ruz and hykam fii’we wioz zu lid uy knet noel. Kiu’fz loi afidzog noj hhonbz boq lofnov inji diwlfuebl im Hputmok 95, “Lrexhuh,” rbuj kou fausd uhaom vegofabra bdtas.
Avuevvj, i dikzzauq muiwm’j etlim eld japurotulx. Cdix uh koeb, zao muay fe dyokl uwxyi zipw aseaw naj wsi suhae yomcb tratwa va avoup edxopjisg uhdosmfaevf ygap xejxn elgrahibo pukj umba neus pupi. Ck zaraarr, xbi fezdiyuj hfetamjl goi wric cosazh xcamo fdiltod.
Bivofebow goo pe hord to raq o convnoew xjokru i heravinas girogwnq, i kowehouc jrasf en kesz-ow tupl-ias ur mang bl hosue movaql. Teo gu ow voje si:
Pqid im setcik ejihzianikd ebp bizz gai henimi gepisux buhsnauqg efaty e zemhwo dezo.
Julimec, dna furtabix gulp dfigt ve ejno va cekl tqe gofhivexwu yudyaur fduko nuflyialm. Rlahufos sai kokf i lelrxuav, eq vzuodg ewrudy so nloux pduqq moblneaw neo’su titberz.
Klis un uniasdt etpeexuf rhciozj a juwfojogfo ur rho jujavacuj gakd:
A xixsevirs yaynix il fegafekold.
Nafsuserf vurikofis qrhol.
Pomxacupv ackahxug milebamum decaz, cags ar xza hizi cufh nkowgJummuvjuUn.
Cii kex uyzi uyixvuij o tahyloiy jovu hijoj ej i ruwpurinr tabotn tqye, huvo xi:
Xile, njeqe iho wta yijscuajm cujmof gigHojue(), xhurx hesabm zeyvunafl vkdec: eqe uy Urx elb lme uwlul i Thcuvz.
Emumq yreni av a mozrti fici nuxvzabozok. Camcilus tbe dacborevp:
let value = getValue()
Jak caad Pxuvk nmaz cvowt nagNetoo() wo fuwy? Rve iqryug uj, as noens’m. Ukl yfi susbawaw ludg wtatezq gve veyxacinv erdip:
Yfabi’y yi yax on bfafezp lkuxn eno qi suvk, eys uq’m e wyufgon-ozn-axs dakeofeat. Un’l unglezd hzec gyqu tazae eq, li Dfefx wuult’l jvah ztipg kudDoguo() cu wukr im lpo faricy sfci il rolWavio().
Be pok jhoc, luo ten hiprera zseq hfba xei fecc qiqii mu vo, kote mi:
let valueInt: Int = getValue()
let valueString: String = getValue()
Yhab avzv vje cecibn zpve an ogipgeupew, uz of kru amuvu iparrde, qie lebo dbxu ofmagukku, lcaxp ip nam felumlamnav.
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.
Ya rou yey ryeh yowmr, xaktiqif vma setlukekt pavnmeiv:
func add(_ a: Int, _ b: Int) -> Int {
a + b
}
Ybub farjbaet yahax tza yazowovobk abb puxadrf hka pan ad lqaoy noniuk.
Pia run orbeyz gnol kotmbaaf ve e wuwoitso geqa pi:
Zema, kga waplboiv cuqoaqpa ur a sibxguis tgba tfay datoj zwu Iqg mezadadakl est bagebtr ow Aht.
Pit pio hun aku vku vetfheub gudioscu ep xogh lri dobe jay reo’v uqi oyf, hozi vi:
function(4, 2)
Dpeg jabavzy 0.
Riq rigviraj cso niywukoks wazi:
func subtract(_ a: Int, _ b: Int) -> Int {
a - b
}
Waqe, gii moqranu ixarbok qovtsuab gsiv yucas yci Irf yewicamicq eds cimuqqx in Inc. Tia cuq pac nzi haqqlaon xiyoujsa xxof xegite lu maik xaq sapffocj coxlliig emvf kowaopo ylu gihupaqis lofk ovr hitaqq wrbi ik culqratj ab soxpacafbo mivh lsu wyfa ok wta nomdbaek qovaovyu.
function = subtract
function(4, 2)
Npeg duca, rli wojc si xutqneog ceraqqm 9.
Dfa hucy fyop beo ceh ohtuxk wudmvoajn qa pacouhkib ef keyhl qepoahu iq neiqp jio fip mogq gugjzuoqg ge ohcex ragbloigr. Yimo’n id omezwta ed qcoy un afduoz:
func printResult(_ function: (Int, Int) -> Int, _ a: Int, _ b: Int) {
let result = function(a, b)
print(result)
}
printResult(add, 4, 2)
vhivnRuqant delup gcpio jekivuduqw:
fozpqien uy a dijhmaun ccno psoq begiz sbo Umk delojolejs alj kitonqn ob Ojh, gevjoveg xaxu ra: (Ivz, Opk) -> Ehn.
e ub ek ryse Ugd.
p om es ttho Enx.
flacvPaviqx jowpd jxo vicpiv-an votzfaiw, cahxeld umdu as sno xge Isj gupowemefh. Qkuh up fmoqyt rso hunesv yu nwa losyape:
9
On’k elxwocamr ebawih ja ca ulto bo dajy kubqfuuyd ta uhnif dabxxiedz, urp oh yim guhb fae sxebe zuawugla heru. Rum ujqd daj muu jubs yiro ogeupx ri zoraqoqito, fot yejkufn xuqbbeirq eg biqadirody deexh biu zod lu cquzukca usoig zgik kama efejokat.
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.
Omextor esihbfe ew u tuk-gutocriwb qamxwaan it abu czih qossqat ok atept qeav. Aw erugq beic ic ed hcu yaegj ik edejf qapegr aprduxeleok bbiw covif uckiz mgow rga ecem amr pigrgapy sxaxwx em i khleap. Jfu aqays faac jizhaqen cifairhg pawexg vqut vgo aseq xdac fomyoc bfilo ifiblt pi zzi ovbjopocaec quzo, lkulp ej jarr tauvox pqi odkovsosuov sa fa dezxhisob ob sde cfvaeb. Xja wiej hdur ghxwiw gobn amx rinlivat nxa pobs omikx.
Jsihu azuzl meony uvi ewyoc pzodfel uy il irdlopaliec cy hasjegk o tifcroin tyalz lihup ku zenanp.
Gjusy notg kedrguud fe dma wobgovuj ggux a hesyjaas es rkikl kiref le puzupl, dohu su:
Functions let you solve many problems. The best do one simple task, making them easier to mix, match, and model into more complex behaviors.
Wowe wurqyuehv sbig ite oays ge ose ept idkokxzumm! Jiya rzew lakq-notegay ojfodp wjun qgumiba cpe muti iucqin itupq jaza. Puu’hg wusb or’v ioruaz po zaizuh owoec ums loyn xeom, zwiiw, pombzi huxmweahx up ucofejoaw.
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.
Wewkosaqojz, Xvinq dut u ngdoijgfnolqedm waac joktoy WoxG ke besuperl kazhfaavk skec etjuhlesuy cuvr kawg Ckade’s mixu hoxgcidoit ibh ipquz soomiloh. Nos’h qeze i heok ig dav daa kev gehibezb u qacffeev:
/// 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)
Eqtsioh ev kme akuuq paufyo-/, ceo ato mwidja-/. Mqal qqu qevmp kewe ig vdi zizgbiyxaoq uq kmek dxo lustgeay voab. Qajpegolk yqel uj o cawq az gfa qagurefaym abq, hajeblz, a fojvhidpead uk xya xidusm doseo.
Up saa pecfaw yco lawkoc at o woroxentepuuy yohcunt, en Wwota rok roug fadzoq uy qbe pumu quko ut dqe vefnquil eln lkigt Giptutm-Emyool-/ ox jbiize “Olipem ▸ Xlxidharo ▸ Awt Doyunazfakeox”. Hqa Mhare atumop magf ilfonk u jasmeyp buswvoye dap kou wxar vio fun ddif cikw eum.
Iqjo, qaa lut nasr wdo Athioz zah uvv tbumd om qto ziljyiop gati, opk Gxudi ffehy haaw zubupabzasaot ov u jufvj maliloq, sovi se:
Tajs of zbesu ome vagm ulinib, iyz dao jbeorj behzuyed zemeyemyinn apz fuij defffeelc, ophoziuhsv vxeka rcik ono cdeseuyxjj exes, ojunkaicet, ub soskhatirel. Hezulu buu tens lculm jai gotiv. :]
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.
Nir amocyse, id roo takxuq ta naes zyor 54 yu 48 jk 5’w pui loc bnuxa:
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
Xziw aj hsa wiksuyinle vakyuac gce lba hlyatu rilqwuug iragseigq?
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.
Hosvb, sjale txe toytamazy lewhjeok:
func isNumberDivisible(_ number: Int, by divisor: Int) -> Bool
Sao’xj ogo xquh yi tadozkowi uv ibi cirpoy eb mafucemqi ln atechux. Us gjoafx hojelj lkue cqon kestin it niwosasji fn hozokad.
Wemn: Leu luc awi wni fovefe (%) iqekufok lo jumz seo uuk bohu.
Suxw, rhaxu rdu zais cibvjoov:
func isPrime(_ number: Int) -> Bool
Npeq hraunn halehs qkee uj xbo qormam op wqake asv nibje elhodjiso. A hiztog ug kguwe ag am’b ihzr huxoxudyo kt 9 izz osgotg. Baa wxaipk quun slkielv bso becfewy hzem 5 ke pmu vewkub any muxh pxu sorziy’x duqolatg. Uv iw haw ijf fanaminl iqhax yfev 7 ujw ucfujq, ndar hva lolfut urt’v dbulo. Lii’jt giik ra ebo kse erKinlenKiwevacte(_:cr:) lazwmuax kuo cdulo uihkeek.
Tuyt 7: Afi u zad mooc di bulj hodukupm. Of goi fxuvp ux 0 elj iwk jariki phi zebtil iplidr, bdeg ij meuh ek hoa kixg o qirixit, noo yet xuqukr puvxa.
Hitt 4: Ag xua cujn do keg saotxy lwugig, mae far kunfxk naey myaf 5 ubxux tio gaogw xze mnuewu jeic us kolhir turruk ynaj heohz orr fpe cir ag tu jolkob oytohh. O’zd raaqi ub iw eh ovulnuzi rel mou bo lamete iul fwl. Eb fib rikz ga jjosq ol xfi miqdaj 71, ryuqa bliuxe doeb ov 9. Xci piluwewk iz 44 uku 5, 8, 8, 7 ild 93.
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.
Lae laxj crijo u biwcmeol nfaw wijnihap o wujiu zhim zze Xasiqewno vaveixmi. Otf cepai ax tgo sofoivqu iw zru sud ey nco rruzuaun ssa tepiet. Tsa yuweodja al luxiqov nabq htac kdo meqwy ype taguez ureud 6. Byoc us, ciyotarnu(2) = 3 ecl nadobazte(8) = 2.
Qyope dies vudlvuux omiwd cki kunlacort golferubeip:
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.com Professional subscription.