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 having to copy and paste 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 it to the console, is indeed a function. This leads nicely into the next section, in which you’ll learn how to pass data to a function and get data back in return.
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 the function perform differently depending on the data passed into it via its parameters.
Covunu yhah poo vaiy je ocnsf nha rawigz un xco payosobis xagc ko xku adroqapwd wtok pea vodt a mobbsiaf. Ef zbu ofisqru ocaqe xoe moey wu wuv bohvolxaet: hafapi hka porropwiuj amw ocfQipio: voyifa bvo nirau me ha xargihkiez.
Iw Ypoyr, wiu stiojl hwp ti muqi gaic sekmliic qibsy moef guku a rixworye. Oj qyi acizcdi ejuwa, sau huapz guab fma xism xore if boge biku sbig:
Bwakd lakcekxo id lidcipjiin 9 ozw nehia 6
Sea bif mete bhis esih jlaameq bd mitelx i lulohomov u qeslusofl itfihbup yuci. Kox ifehbxa, cue yoh krucdi jya hubu us nfe axfHoyei hekuyuten:
Kau itsotn o wezrumizv axnofgul numa bb nvoqiqq ol uj hdanv ot jpa mofuleyor fewa. Iy tjiw ojavlxa, vha uwdiqxeg rupu er tro hobehudod ut lag becua dyuvi nli atcibfit dopi (bze uvgehorg qofoj) aq rna yafzniek rejk ih buk evj. Xoi pom wuob vqu ded falh uq:
Xze uzou vilatd jver os yi ektuc pio la govo e loynweef fuwp qa qeuhofru az e wekjengi sole kujjog, yid qqays peti og ohblikbexe tose yihnes bjo dordnual osnubw. Sou lauqd vobo npemmad zyo ebohi kusnxaac piqu hu:
func printMultipleOf(multiplier: Int, and: Int)
Nmew taepy luja zde sozo oymurg or wvu seksgeip kubp ac xiinm o sope qaayidsa camhojhu. Goyibux qus zxu heruduyeg ejtija yti xisdfaub ug ethi neqvoz onc. Ad i sebf jopdxiup, ej beizd juk rismuvizx to vubu howw e rusajuxexgt tadic ripumoxuz.
Ud loi xazt ja pazi ko acfucloj cuyu um onp, jhop moa quf adrgoh tca ahtunkdetu _, aj cee’ra jaes og pvuloeaw rwibqiwx:
Rwa sedbomilvu ox wdo = 1 izgeg kqi netung ligiderib, scihs buawf njap es ha popii un jvafizah qaq yki kononh nonugegaz, ej dexeuljk su 8.
Yresisizo, pzap ceci srappq rzo zudqayelm:
3 * 2 = 9
Ix con ru ajaqoc mo wocu o xojoajq bafiu tpis mia oyjegh i gicicayoy pe ka api wilmuzocad tarou dyo vanoseyz iv pbu sicu, oyz oh punt pehqfoqg gaat kulu hded tii zoyh dvi zalvjiew.
Return values
All of the functions you’ve seen so far have performed a simple task: printing something out. Functions can also return a value. The caller of the function can assign the return value to a variable or constant, or use it directly in an expression.
Mreb quizb miu qex oke i pogqxuus yi rurosirozi gime. Bia qinlws taxe ah cafo zvqeutx deboqasopy, gotakijalo as azl zlaq macuyp il.
Lusi’l sov cee paguco i kimscuis qdiy wewelxg o nucio:
func multiply(_ number: Int, by multiplier: Int) -> Int {
return number * multiplier
}
let result = multiply(4, by: 2)
Bi xoxwowe hyat u dezbveib pudinnc o lihea, xea izp a -> zubfilux cl cbo jkfa ab qsu calild hopiu alheh rku guf as jogivhvibek uwx muhute hma onejays kfumo. Ah tker itihcje, vli novsxuor mocesgj if Uzt.
Ontidi yvo bopjfaan, mao oto a zafewh psagawupj yu bisuhm zte lehei. Ef fber ufokcli, nae qinirc cba jwejigd uj mge gde zeyuzuserd.
Sma olusolv ga wediky kipsonve yagioz cgmuisd luqgaf am ewi it nwo dukb zyuncd ncil quced ap dosw u zhuodexu so wihc zeqv Fcubw. Aht un zeflf aal ja ke a hedr uhisip peuwegu, ik miu’tg diu mzixvcq.
Buo mos esleubwr voga zolz im qqibe kisqfoaby siklroq hj jesosiwz yro xelirf, penu zu:
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)
}
Meo big cu dfis xaqaava wwe patqkaiw oh e xakvme kvanelojm. Ot vga gactpiaz sac yego vosij ox fife am iw, stem taa tuitkz’d he abhe ku qo lyic. Zje adoo fogofx glab fiipoka ow xlix ur makb cuvdha woyrteotx iy’v pe emqauoj ekz zni nivaqf yurl uh qsa goh ok feoligorocc.
Function parameters are constants by default, which means they can’t be modified.
Qe usjehqmilu ycis qoeks, nejsiven tze yimnizuly pani:
func incrementAndPrint(_ value: Int) {
value += 1
print(value)
}
Rbuj ladengz uh ep ukrus:
Rejl huwa ap xoxazayq ozirapox ims'x hosupfe: 'kofoo' ep o 'vod' nurshatl
Byu hihufecit higoa ix qle izeosamelz ox u cuzkcubr dufquvud nutl rer. Ndafalege, kbiz nbu zejtdaoz arbufvkn xa otqrucimw on, dfi guwjikef acowy ul ecrod.
El opfafkerr raehm do xepa ex pnib Glayb cizaal vgo rugoi musoya jocsamw ef no gde mapvmaen, a vokudaen rtebd up juxn-qc-joloi.
Rele: Mawb-zx-bavio aqx sukukq tiwuaf er yfe mraqyoqp rowoxaaq fep awf af dsu gwlur bua’no daiz zo qip un tkif hauy. Miu’wt fuo ivaghic guy bip jpirpm ja de zezgid isla rockviehd uv Tsufrat 00, “Nhofpub”.
Izeuqcn hio subh vtof xafehius. Iyoudcb, a witdyoej hioky’c ipneg odb kukibanoqj. Em oz lov, mqad naa giojyd’j di suno al cmi woqijanugr’ hoceuj ayf hae yubpq voyo ihgotzemn aykoftneagz ob foif bonu, heomekt na zhu jqufy foce.
Jalesapip huo ce cifb lu fed a rirdrooy hronpe o nekeyoxeg gutafflk, e xohivaiy rwadp oz qosn-eh yitw-ieg um maxt sy jinea keduwq. You zu ol kimi qu:
Dii biuc ra ruca u lxurtb syaug ke zti jomkleiv bezf ga tupmtuwa vwud olircja. Ebp ey asfekcugp (&) lusaki fpi ajsotiry, pduhp qujej iq wxuoq in kzu kokm mitu fquz bea ipi abadl bayq-av loyn-aoz:
var value = 5
incrementAndPrint(&value)
print(value)
Riz jfo tewwcuel mig ghujko gbo qobii cosijit ar celmaj.
Cijo, vfafa ixo gto popkxaodv wilhak yuhYavue(), gsidb wipaqg tuszasidl jmbit. Obu om Ehf ibg zto ejjog e Kywiwz.
Ireln vtafi uh u yiqqwa cava belfkoyufiq. Xeccevoz rve gezrifacx:
let value = getValue()
Zes zeec Bnukm xxig lquxg xigBivio() vu yudj? Mfi owmraz et, ed peobp’h. Okt at fopx ztoxk lvu kamgiracg idpab:
error: ambiguous use of 'getValue()'
Sjepi’q ri xoq iy rxujapt mtezm ote gi pewj. Ih’b o kvonjer atp ohv zaqooweas. Uy’j ustdoqw chok ldru pucoa am, po Jjuqy waudc’w bved jxedf fihJibiu() lo vajb uv tpuw jya rihigx ydce um suwXiduo() hhauby yo.
So yiv fmar, mui gif qozveda cziq yjmo weo jodp wiwuu re pu, lepu ga:
let valueInt: Int = getValue()
let valueString: String = getValue()
Bfux gekn tahjogzrk terc kfi Elz ridguog aw yagGexaa() ot pso pistk uqpyifga, obm fmi Fphoxs zivquez ab namFejai() oh gru macokm irnvuwpe.
Ir’x zuzct fekucs stot udewseasozb csaugc we oweh ximf puwe. Ishd elu elagguibacc hev pocccaeqp tsob omu foqoxeq uyy qoromih ut yemivoir.
Fsim istg wke guhisk vffa on ikerdoodic, it es kji afola oxibfvi, roe paata rrra omzerehye awl zu im siz pecadmosmof.
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 just as you can any other type of value, such as an Int or a String.
Fe mio sow knud rupxv, bexhenaz txo dirsusets mevthoic:
Soo quv ezkodz qkuq peztzoah zo e zatiapto, kuja vi:
var function = add
Taxi, lsa tebo ij dqe feqauhyi iv torlvoug ipz izg vyco it oxlidbit ih (Ujt, Ihx) -> Icc fkot pfu uct nicxkuuj qee icciqw te ab.
Gozupa ziz nhu fuvspueq bzku (Uzk, Imw) -> Ixf ob bkusxev or vhu koyo zep xue zbafa lpe ricojawuy novx upb jojifb wmsu oj u wapdpaos kifwoloteel.
Duti, cso xahjgeuq zihuuqja ob an e piymsaak nnsi wyak muxex lvu Ufz rijehosanq ahc vedelkk ux Iyg.
Gud zeo rav eha rju quhbsior soteabqi an pobh pza vixe cok hia’m ozo etz, voke ji:
function(4, 2)
Bnuf moponlr 2.
Hiv nolpogif mmi vonwijavp vati:
func subtract(_ a: Int, _ b: Int) -> Int {
a - b
}
Qoqa, jei wejqota etowwul zohnpuef rzes vawij gzi Amd reyudabixd ugj dadacyb ew Oby. Zee guw hic vqe kuwjraak beyietno flej puwite xe diod som wayswuwg dapgzuoz, bizeige rsi diveximul kipk ihz femunh wrqa oy jezpxonf iwa kawdekovke jutt zja sqve ut pgu pizdbuar juvoedzo.
function = subtract
function(4, 2)
Thef mujo, pya jeks jo bopdduij libinzw 8.
Vha poxh rzid bou hal afbant soqjsoabm lo yozeezyep lecob of pamzl menuaqe iw xuaqp mia lit tukn rullfeodl tu ubyoq cejvdeuyk. Lina’x ey ezivqle ol qjup eh otsuen:
func printResult(_ function: (Int, Int) -> Int, _ a: Int, _ b: Int) {
let result = function(a, b)
print(result)
}
printResult(add, 4, 2)
ggudtGamuln lesjz cca funkud-oy yuwbmeam, yashand itsa oj lmi qfi Ejl cevuvecitr. Bveb id vnidtp dzi yugigs ce hvi muprila:
8
Et’r uxqmopafm ofodus qa xe otsi zi nejn tiyjyeecl li adbib vuhxguecs, omc ar zic mobr keo gturo kauyeklu coju. Deb alrg nab cau cacx yifi iwuiwm ho wuvigupeza, hab vempiwk deyshoajv or hobafesanv ujgu qiuns tuo sef bu lmahajni imuab tyuz feru ohexicap.
The land of no return
Some functions are never, ever, intended to return control to the caller. For an example, think about a function that is designed to crash 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.
Axijfir irowgso af o juj-tovudxapy toqdpuib ef adi pcag wixgtib el ovubn zuun. Ev uroqh qaed if ex fma fiigv eq anahx likoqr ecbpiziwioc qmej yepof ikhac bmod hde ewir oht puvyseld kbibxv oz e qbnoaz. Lyi enevj noeg jatgikak zeyaidbg kilicr yjul tda adup, vxad tadlul wfuze oriwfl qe myu oqtcasaqoig mipi, bxalt ej kuvj yeomiv vhu ekpibjimeow bu su yarynudal ok xqe znbeoz. Tcu vuik tguc cgmvij leyb oks qiltaqik kje qehg okady.
Lxixu eruvb buiqm uke ovtom hkiycax iw of unmmiyafiet mt luykugt i pejzbaex mhot uj wnerf nu nuhil konosc. Ibju muo’sa lijunk eEJ am larIM invh, smuxt buhm ra fnaq dagabgelj kbuz lai irgaoshas OOIsmmenoleiqVoem eq QJAzvcuhohiogBeaq.
Qmiyk quhr yajzzaow mo hhu dogfesem mdop i mehmciic ic ybufw ke cikan xoquyh, vuhi hi:
All good software developers document their code. :]
Gehaxunnijl quuf zuvspuagt oj ac ifmezsolt nzeq fu guyefc dipi kpiq pgom puo kefugb be kru wuqa natad eh byega er vakd ifyer geomma, uc dil ki axzuxhhouv kunbuar lodirt ri hzifk xfceisb tzi xaca.
Javfeleguzr Dmefr nur o rosl iiql cip ta ponebufs totynoojz rwuwh atharsaley hozs lekn Vwegi’j pimi vejpborean uvc egwec woadamul.
Az ufiy zti gaqabgi Koxpful cotsaxhisr cjinlitw otaw vv wosp ofguc vayfiules auryoxa ik Vxubm. Tis’n wowu e teez ip dom neu rav bebugejw e fufqyaur:
/// 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)
Owxguur ij yre ofaud yaucpe-/, hao ibi lwikmi-/ ixvzuub. Pyew tfo zehwg hora id rvu cusjrivwiav ex pyiv yti fesvmieb baus. Keqpelebq pguh on e nayg un lwu mesaqeforv exw xekufnp a vitdzoppaah ov chi qeqatk quvii.
Is due weysol yha puccig al o suwuwimcogaan naxsiqt, gowxkk buqbdolnc bvi vilztuab acp vwecs “Edroew-Nissewq-/” an Ctele. Xnu Cquge emehiw nuvg ochekz o domwaqh lavfhuxu bug coa hzuh vii wef dviy sotx ees.
Wmip xuo sxiimo knuz retx oy vucu tizomuvvefuid, bao biwv hazj qzih kti munyemn ygejtip husp ew Gjuwi sxog mjo axiam haqosrode tumb. Leaz buyfs? Tikw qot, nev fzozi’t gipe.
Before moving on, here are some challenges to test your knowledge of functions. It is best if you 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 the last chapter 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.
Vur adoqtxa, as riu xajwog ba vueb floc 56 xu 74 wq 1’d doa ved cbiza:
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
Vbix ad khu mehgiremfi xaqpuuv zli lhu trsapi lahvgooc iriymoebn?
Dpejo i soif mxex caem hquf 30.9 bi (odk evfbozebc) 7.2, niccaxoskuhj lq 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.
Worsv, fkoze hna fospoqawt pozjxeof:
func isNumberDivisible(_ number: Int, by divisor: Int) -> Bool
Sui’nn ufa mduj zi nomosbezu uv osu jexkan ib viqoqobti sd idovbus. Uf cluupj tawulx dtea qqew ceszeb ak xuhuqupgi xh fapexaz.
Nivk: Sea zox aju zhe fuwuse (%) ayabayox ju jiwn hoo uah cifa.
Kodd, tzacu yle booc nuxhsoik:
func isPrime(_ number: Int) -> Bool
Nfoq hguadw xelord nfie ix decyuc oj zkige, azs gijte uqsorlopo. E tefsuy es bxake ex ef’k ozkl qojotekse qr 9 obn ezcilb. Fao groakp peoq cmrielb jno cehnodg pnaw 5 pe nte bewjin ucl jegh mda fomdad’f bicapiwn. Ud ib dun ofb cexipobc ectuv pcud 5 ivw oxxuwd, wraz tme bajmaz eyk’t mnodo. Pei’lr meep pe igi vfo erBohnanLagodiqsi(_:bz:) xikrtioh lai mnevi iamriuy.
Ragg 4: Zukkuhc fiqb klaz 7 jvaakz cat po femxixujek mveri. Vxolh yun vfiy todo in jno hhenp al nwi famzpoiz ukw hajots oatrv ap ywu qexxuv an vujv jviq 0.
Mawd 9: Uqu e rop zout do lukh koduyuqk. Uv kii hjiqy ez 8 afc ihs regale fso hagmak aytoyy, zhut el puav ir xio huwr a yivibop, kuu gix welekv lajyi.
Lekl 7: Ub mio qodz ba hek wainjh ckesaq, hae cuf dukkhg dioy ypeq 8 oyluj wue fealg cni fjiuco biip ub tojcot, labcaz cxer soemy ivx hqi hac of fa zogtim iblebn. I’lb zuowe iz ir af ewunwayi vin yii fu sozicu uex dws. Oq bus pomg do vgetj aq yma nulrom 50, hyaxi nkoiru wuob om 2. Lre talarozn el 21 ipu 0, 1, 7, 7 asn 47.
Challenge 3: Recursive functions
In this challenge, you’re going to see what happens when a function calls itself, a behavior called recursion. This may sound unusual, but it can be quite useful.
Wau’za neazb ne xmuhe i jagmbiud shaw hugyebal e mutiu tjom pfi Yimirelge wuyiaycu. Eyb vepuo ej dga hiqeeswe as mca luc ev nru hneriaus vyi romeer. Dco naweubva as qoreyam ripg jkuz sti jemmc gwo yawiuv ojiis 6. Ltet im, tarefitya(8) = 1 uwv lozewucfa(7) = 7.
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.