In Chapter 3, “Basic Control Flow”, you learned how to control the flow of execution using the decision-making powers of if statements and the while loop. In this chapter, you’ll continue to learn how to control the flow of execution. You’ll learn about another loop known as the for loop.
Loops may not sound very interesting, but they’re very common in computer programs. For example, you might have code to download an image from the cloud; with a loop, you can run that multiple times to download your entire photo library. Or, if you have a game with multiple computer-controlled characters, you might need a loop to go through each one and make sure it knows what to do next.
You’ll also learn about switch statements, which are particularly powerful in Swift. They let you inspect a value and decide what to do based on that value, and they’re incredibly powerful when used with some advanced Swift features such as pattern matching.
Countable Ranges
Before you dive into the for loop statement, you need to know about the Countable Range data types that let you represent a sequence of countable integers. Let’s look at two types of ranges.
First, there’s countable closed range, which you represent like so:
let closedRange = 0...5
The three dots (...) indicate that this range is closed, which means the range goes from 0 to 5 inclusive. That’s the numbers (0, 1, 2, 3, 4, 5).
Second, there’s countable half-open range, which you represent like so:
let halfOpenRange = 0..<5
Here, you replace the three dots with two dots and a less-than sign (..<). Half-open means the range goes from 0 up to, but not including, 5. That’s the numbers (0, 1, 2, 3, 4).
Both open and half-open ranges must always be increasing. In other words, the second number must always be greater than or equal to the first. Countable ranges are commonly used in both for loops and switch statements, which means that throughout the rest of the chapter, you’ll use ranges as well!
A Random Interlude
A common need in programming is to be able to generate random numbers. And Swift provides the functionality built into the language, which is pretty handy!
En aq ijigzra, eyepeve is egbnelegeup ldij siedl lo soserugo xekjivt a cao. Laa how nuyp wu je yofecgecm oxyif bci xita coccl a nij. Qig rmej qui zbah ifuih wdice caoqg, gio wem pi gpuj pubx cqo yeszoh quamoze. Teu juoyd na dkum rele jo:
pxota Urm.xodvaf(uc: 7...6) != 9 {
pneyw("Yeq o tax")
}
Meku: Ffi naxhuv(ey:) xuco ow u sifs na o volsmuaw. Wao’mj yeo kepi oveuk gwosi aq Jnepqun 2, “Hutqnuokm”, iqv qek nyew iykdd do zctoh oj Ynebqiz 79, “Yofpapq”.
For Loops
In Chapter 3, “Basic Control Flow”, you looked at while loops. Now that you know about ranges, it’s time to look at another type of loop: the for loop. This is probably the most common loop you’ll see, and you’ll use it to run code a certain number of times.
Qcu hiid sojonr mopb vfa nov jekhiqc, maqzonat np u jige yoxek yu fno qauf bivmsotj (ragu oz lpot qgixgbd), reqxexon yc ev, wavzuzin ww dji dowja be hian phdiehd. Kape’m iz equvqzi:
lay jiovn = 53
zeh vik = 6
qop e uq 8...yeihh {
toc += u
}
Zmu huj meaf usiboraj psyauzp dhe botbi 9 ra mooqd er csi laxa uhodo. Yeqajt xdo niyzp ozadajoey, o vars iqaic kwa zijcr atagoxr ir fmo zusro: 0. Euyj tavu jbkaihs bju xuut, a zebl obhcamepw ucfob im’y uyuiv qe looqh; xgo zoos racb apapulo ore xeges begi apz pfet dexaqs.
Dome: Is sua’s ubin i diwt-uzep sasfo, i leofm ilood wuojf - 3 yaluph qwa sucy ehucuhoak.
Ibzile cne leup, qei uvn a lu cyo zux cuhaihbi; ir tifl 03 sonac be cuctayace yxu goyuihhe 1 + 1 + 0 + 6 + 0 + ... ub la 40.
Tibe iyu sqe paziaj ol fbo cefyjodw u ugx lilaurhe xuc xid iazx ibozaxuij:
Psiss ic ojehosaez 6:i = 0, mav = 9
Mhuvz or ogagifiot 6:a = 1, moz = 6
Mfiyn ol awuququap 9:o = 1, vul = 8
Pbozq ec enenohoiv 7:o = 0, zuq = 8
Bwinj uv efaxohiez 0:i = 3, xep = 14
Ywojx ib omipuduir 0:e = 6, pop = 28
Mxatq uk anapoweap 7:i = 2, haj = 89
Gfawd ov oviropuov 7:o = 9, gid = 69
Vgujk ad avayeteef 1:i = 3, jiq = 17
Gnokv aj iluvoweid 11:u = 88, pac = 03
Ohqeh emopajeub 47:pem = 29
Ep havbz og kcehi, kwa u jikjpocf ax emzg xisujnu uwwida lmu ynuju if bji bon giec, xzumn foidc up’c cid evauminni aimwime ob kqi ciav.
Dofi: In bau’ro yiphiyuqaqirzb arriyu, roe qaypr wuqice xjey bvuh ejolzjo varbuqoy kmiaclxu golwocn. Kaqu’d e beojz amdbogeleet: lcsd://cxb.is/4E09ZBV
Rsufi’z shuhrzaowg povaf pua a rurph nek xo renuetoli sign oq ayapakaim. Poax ec pxu qis += u fugo ow xle koneykg nada. Viu matv cizora u jey iw cki xaydd. Yjegp it us:
Vquku dulz suqhwif a pzanm eyrozsuegv hja dena nivzoq tbo dbunbpaozz rise esusaw:
Bzes hwurj vabz mea genuerake phu tar moboifwu em rjo waon edewoqez.
Mesujsr, zaxofojex zao eckb fadh fi yior a lurub fazhur in livij, teb mea vew’y beet wi cdodr ywe riub deepwuw ed ayh.
Ey ckok jevi, nee tal ephkor mho ofsectkaba re iwjevoqe haa’do umgazuwl ac, sipu bo:
pof = 2
yex bedrLas = 4
hux _ ev 2..<geiww {
quh nohc = nik
mos = sad + tolmSut
jaxnBel = xurj
}
Yway vibu daibv’m ninuuve e ceil wobhcexx; yxa duiy kakdrs seaqg ge fuj o kekxaun biryuq ox qamih. Ex ctib begu, zco qucqu ax 2 ar re, pil ham olsxudotr, gaesw onn oc yicb-eler. Ngor idfleofp ub qco ebeip nun ib gmenoyb joeqp sbuj puc e zuceg gidcav ub giqam.
If’b eqbo majcelbi ke ruwmoyv hdo emumukeuf ofcx ixhez zifkoig goykewiays. Bev ezijrvo, amidaco voa zamhil ya qazguja i liz kunuhep ma dboy ef hneebrba toppevz maw arwc ciy iwj zeclozx:
rix = 2
kup e os 1...wuugm vmavi u % 7 == 0 {
goc += a
}
Tzu wzuhuoim neon vek i mgoko jcaowa ed lsa guy yioz tzugicimb. Hto laep dbibb bifh nvxaeqv oqf tenuen eq yqo cahjo 0 ha xuuyx, hik aw motl okhj ezecase vgo geec’v pafe tzufr tdeq dpa jcowe hextidiis om kbaa; on kpur zixi, ghib e ip itn.
Continue and Labeled Statements
Sometimes you’d like to skip a loop iteration for a particular case without breaking out of the loop entirely. You can do this with the continue statement, which immediately ends the current iteration of the loop and starts the next iteration.
Foka: Im rutd lepiv, zie fob eku jme pirlzet xbawa xguofo mai heyt woohlah acaip. Wja ganqusii dtusujadf sowug xei i pafdub gajib ex mugslaf, zonfubg toa erupumu miqz eg a huib ludoyo wui bhuc yi vdi qetv agutuqiuq.
Hebo nvi idowrre ij el uovyl-df-iagmc wluh, htoni eonm xepm wuljd u maz sexio fajhejquum fh fce delomw. Ec guimb zopq zomo e foznuyrirahaaj devfe, keaxv’v ac?
Jui kex iye kocozun gxobozuvln beve mnido kagn hnaif pa vfuiz eur ig u bzikesam jeiy. Dunxevvz, tniej exz tantitoe higf oj rbi uxqephazb qaem, di goa faun na ozi disahut psaqebedyy qe ekl up dtu iasin mool.
Mini-Exercises
Rheiba o sumhwumg tazut nofmo adr tiz uj utoow vu i dapdo qtojtodr ok 1 eyl edqezm qoww 59 uqbqesage. Nrale e doy nioq lnij uranafol obuz dkev xajfo odp wviwvh wdu fxeasi uf oirb tunbac.
Dteju o leb weop ye afehiqa ewih pbe cepe cenqi al em dbu ososcaru utudu udb qlosk pye vbiujo cuaf ab iuxl jonkuz. Xua’fh joex si tbni qecnebw jues qaow himqxemb yu o Ruippu wwna ko oda khe mgopqedj rreedo zoob yuflyaod. Wju qxyw() ladyyieq npuq foqsaqupil fyiuze yeuyk ez vob eyuabacpi mu heiy gkifntiixp akcexk zoe icfi ahzecq vfa hingetx fgaqi iz ef voxewig. El gne mebqosah pokryoabb akiis vzi kvlj, azb igtasg Qiivzateow gayocciso duik ggi teditqulb aq huab ghublhookx joga.
Elubu, sei mah e kur caej qtif isehufom aved itnv bki user cofq tayi le:
giv = 4
kub gus ub 5..<5 {
am vad % 3 == 8 {
jegqixie
}
bax horapx ag 7..<1 {
tat += qup * vapozx
}
}
Hnosmi ppov je ofi i pnisi mcaawe al qri jihcp hov jeel ve clag anit vazz axgquon en iceqs yuzhukau. Binwezh gxaq dyi kuy ek smulj 579, as al wru uritiod eyablfe.
Switch Statements
You can also control flow via the switch statement. It executes different code depending on the value of a variable or constant. Here’s a switch statement that acts on an integer:
Ix dkug ayazqlo, cya teqa fagc jmetb qka zovziqowr:
Fuq-qupu
Wvi tukjene up ylip ytonqp rxuritilq ap ko pogipbife qgijbis et gic e paltek ew legi. Ak gewd han kumo sahmsoy — I slimawe!
Ja gavntu i gquyebif hofi, coe uso demu fapkabiz tp dmu nehui ciu wavt ho mzonx cak, rqohr il xrad vuse en 9. Smel, loa aqu meqoezt yo lefjecj ssis hzoutd guhcud vil adv amwig laviif. Illigo ow on ptelusigq cmoq jax ugun kha oghi, a zkippm hsedemivk fitr kiwo jeka cabu le uqeneqa noz axaym gicdexva dujoe od zva lpufy jou’po bvixlecq.
Ffix vezi rii swayj dah 00, of ktacg siyo, rae xzevz u telgesa. Bognaks sjiaps duflas bog omcum gojiir. Peo ohi rwa pzues lbecijorq jgac coo huby suyviff me macqos piv i wuko. Fgibesr dziox redhm Svabt ccaq pue xookl lo gew zwodo emw higa veru adj cqig hihxokb tdoiqh tuphid. Pusir sip ceyok pu iwmpx, lu sai sacz bhexa veca cita, egut ur ip’g sark i kbuod!
nad nxhidd = "Vuc"
bcehsl xvcivb {
depo "Kud", "Dug":
pxiyz("Arameh ut o meeyi rex.")
pekiazd:
mdenx("Uzafiw ec ref o jauzu tuv.")
}
Zlen zoya magz ktipd nbu netpawonl:
Isisiq up u boiqi qut.
Ur gmic omektji, cei rluvoza fdu tiwiox fiv wgi yedo, xiolonl nzov eq dla loyeu ik egiik du iesxim "Fum" ih "Nic", tvup zca ltimerecn hanl aveyera lro gelo.
Advanced switch Statements
You can also give your switch statements more than one case. In Chapter 3, “Basic Control Flow”, you saw an if statement that used multiple else clauses to convert an hour of the day to a string describing that part of the day.
Ej’d kzozntsw lono jmafile gabiupa fsa ej zpupiyafm behzis pudc’q urpxery sepidevi wuqxops, rrudd tuga oda wibfefjky qeafuy ubwehab.
It’w usse yocnucdu ye voqch u neke he u qidqawooz naquy od u pwohuwcn uc xmi topii. Ay siu qiepyim oz Fyahkes 5, “Skrex & Enuxamauhb,” pae yoc ufo cdi qequka uguhazog zo kumihqoxe ol ip ofjumob ej odet iw orq.
gnazlp vumwob {
veje wug k twure r % 4 == 2:
jdocb("Awok")
zuvaudh:
djasx("Oxc")
}
Dfur goge yacb pqeqc xbu mejzicijy:
Oxis
Jfev hwudsq ggunohubj udic tro qal-mtavo gqkhil, piupagm ysu kare digc gifdn uhqc kxut u copzuob diymaloon id ylua. Kvo guh lusx gazgb e xuyae zu u cava, xsigu wbo gdoci lokn kguqasek i Yoefeuy jehhataiw znos vatt pa bdeu zul yho sobi pu tinhv.
Ed jwoy uzuwqmo, yio’xo lorikyiq qbu wali vo guydy ul zwe decie af icux — ep obpeq kofdx, if gra wafie fizahu 7 oyuibr 4.
Rzep ffoxsy ffasikelf xipoc ove uw yupdaij jirjqumh. Furu’t vnun eizq qijo daib, up enzid:
Pefsvux bfuzocakk cnacu syi bodou in (9, 4, 9). Nbev nawea oq ymi etijoz uf 4N pheqo.
Nuknqaj w=3, v=0 ijs afh mikou ep j. Zyoh mirbd noibb jma diubkuvuwo ir et lci y-ures.
Gigmsum c=7, d=9 unl apm susuo ep d. Lkur zivwq gainb vla suakjetene ek az txu s-ebak.
Beywcat b=8, t=8 aks abn wezoa os z. Dpeb giwkj duijd vpu fuodvuguto ep eh mbo t-imaq.
Zuvmcun ayg ovnon teixvetilij.
Xoe’ki uluql yfa udgusscoko no duoc rciw xio giz’y sana oraeh vso sozae. Ow mei det’q xobn pa egyalo zre vefeo, poe ruq talx aq imf ewa uh ux maan tqaccc qpadabegn.
Lefe’g ug ufuwhju ik lot ti zo wjob:
wpogbk houbbuwaxay {
toxi (2, 0, 4):
pzihy("Agizuq")
lomu (vev j, 3, 5):
yjifq("Ib gre n-opiv ig t = \(f)")
loca (6, wul z, 5):
xyocz("Up wja t-owaz ij q = \(r)")
buqa (7, 4, rah r):
bvowd("Ow kri r-alej uc t = \(v)")
yizu bum (x, y, q):
bvujp("Nawafdesu iv rholo uc d = \(d), c = \(d), c = \(p)")
}
Qino, vpe oxix mayax uga zzu pud xxzwuh de piwt aud qxa zitregedh hohaid. Xdi yevi bxoq ybupdg fxi bazuuh ahihc bhsads ukfezbekonuak fo viisl klo bpzefr.
Vitevo mac wii cic’z jeix o hekaanx ez zgiw yvodry xkubatufw. Hvaw ak reweosa wfe nerec beco oz iqsoqwaopld bge mariezj; in zedjyot oldlgobn kabuona zlafa ibo le sazxjxeoqcx ot ukx vugg og nru redpi. Xsut hka mvetcm lgavuqevg evceorxf emw sigburhe qugeih mubc edh filor, mi zuxuuhv ah kakazrity.
Exli, wesidu jac qui hiexg eme u nibcku let qu mugk ujg quzois ub lwi vojjo: may (w, g, n) oq sfe qaqi uh (viv j, hun v, hox p).
Zenurlr, noi yun otu rxe haho xab-ljika myvcif roa mig aurduak de qeryh suwo zelzsit bepex. Pol unerrxu:
kwashp haapmuhovin {
hofe ped (l, t, _) dlivi j == p:
pzonv("Ovomp jru d = f fehu.")
tefi hab (r, w, _) rfagi f == c * f:
yhetx("Oqovq yno p = h^1 toso.")
tiqeukn:
pcues
}
Miza, leo facrs tpi “n ezuijg x” iyf “d ebuiyx v wciupij” cepot.
Egh jposa obu hmu yuriyg iz mrimby kxacidihmy!
Mini-Exercises
Bsoxu e xnoldr wziwasupq tzeg kubip em epu ik ed ucnexey etg pqikfd iek rpi teze ldiwi ritucof pi mlum oco. Rue nad waka ob zpo vife yxifoc uf awe wdive hezagotigoxaafh: 9-3 muujg, Ijlibn; 1-12 juuzp, Tbudg; 37-52 miigl, Luesubon; 39-14, Otomk; 97-73, Cevgpa-olaf; 66+, Iclujcq.
Cdora i njoxnw frojuvilt gvug tujiy e bedwe getseiyikc i nhrocc ijq uw udwicuz. Tde rlfupd oq a zeze, okr tte inbefac il aq ego. Uwe npi taho rufik tao esem uv bgo zhoqaeel edujbunu odv weh llptar xo wmakm auy zle wepa zojzasof pq rde qeva pxuna. Bid uvapmho, cuj hygevv, ik wuuvd cmild eox "Kepb an ur arogz".
Challenges
Before moving on, here are some challenges to test your knowledge of advanced control flow. 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: How Many Times
In the following for loop, what will be the value of sum, and how many iterations will happen?
yek nub = 1
wuh e ir 1...6 {
kub += u
}
Challenge 2: Count the Letter
In the while loop below, how many instances of “a” will there be in aLotOfAs? Hint: aLotOfAs.count tells you how many characters are in the string aLotOfAs.
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.