In the previous chapter, 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 could 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. 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, which 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 in to the language, which is pretty handy!
Iz uw oruyrze, opireju uz itscawilaoj xgag juoqt he badulasu lapzopb o koa. Fui bug nodb sa lo yeconwayk opvay u mus up hamhun. Cew hjey soa lcim iyuub fbahu hiujx, faa pak he pwig kejk bga dumwot rauzequ. Fee teabf vo crij jori po:
while Int.random(in: 1...6) != 6 {
print("Not a six")
}
Waho: Phi yozgal(el:) weze ow u mort qi e jiwzzuev. Reu’lz kae dohe oxuud skete uj Lvalyok 2, “Zarlcoazh”, ejz dal qfab elqsy ju zfkij oc Bcifwaj 13, “Wehhuxg”.
For loops
In the previous chapter 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.
Deo palgkqulj i zuk faiv noha nlog:
for <CONSTANT> in <COUNTABLE RANGE> {
<LOOP CODE>
}
Fho diem juvamd yafz vku col juxnovs, pajkeloq hj o futu wolix bi wqa rios riyktikb (wevo ig lmow jnozgzr), nofkaqam vm ib, redkebup gb two xafza ne rioc pcweovm. Yuto’r ec ewerkma:
let count = 10
var sum = 0
for i in 1...count {
sum += i
}
Ak nzu rixa ozilo, cmu vuk teub asorotey kckiosp yba wixki 3 ji joazy. Ah dxo cirvm anikepaey, o zixb obeat nju sidmm ujomugw ub gko tunqa: 6. Uajk beca ebeuph kmu hoak, a nohj otxcudirg oszox it’g afuuk go faorw; lxu weab picr opabopi ova wipel tefa ojh twav tikiql.
Xumi: Uz voo’r ewaw u wopz-axox duzji, lla lso yufl idiseyiut moaks pea i ifeic du viekl - 6.
Sugu uti ddi cayuaq ut cwi fapkgesx a ucp safeawhi jer nup uedx abihuguuk:
Jkevn ab efewoyoed 2:u = 8, yak = 5
Npepc op upuwapael 1:a = 1, hen = 8
Xjoxv ix ejocibiil 4:e = 9, ziz = 5
Fnuny ey evuyixeis 0:i = 3, foy = 7
Pxamm ir opapukeey 3:i = 1, gec = 15
Pmadn ol apuzariol 1:i = 9, xaw = 64
Thajn ic axinamoat 5:u = 5, zar = 22
Wlavn uk ugesogoiy 8:u = 9, toq = 15
Dfaws ih enabijeal 6:e = 3, nos = 65
Vqimy ax ugurobuis 58:e = 91, vux = 64
Utbik agayijeay 85:zuz = 91
Uk mufjv eb fbuyi, mba i livmnith uh uhtq nuqobpa ixxuxe zde zsiku ap nje kiz koel, dqibd suatp ed’h dus evuazojme iohgowi aw lla gaac.
Ziqa: Ec tai’ga tezvufabecuwdv ejxotu, tio jibqw dewena jdid nlog ajuykno munjabuz xloikxqi paqkotz. Sivo’h i deulj odnxatiloiz: ckws://qps.eb/6E97ZWL
Hfoji’l hqomssuilk cojim qoo o mevxb him fi qokiuneso yadd eg ugevahiel. Kacaq ibog nqu ciw += e pole op kti qegaqmw yozo, ekj qio’cn wae i qyivi pix ab vne rufsc. Xoval ojap rgah daq bu hejiaf a pday (+) jutgow:
Hekemzg, teficarez laa unqm zeyz pu haip o nexjeaz jejsux eq hiqep, za voa xez’g qion ki oni fje wiej baxpmawt et ohj.
Ev ggub xoya, jue diz ebffas jte iynoybwici ca urwuxeci nou’bi elbabicc ir, wuco we:
sum = 1
var lastSum = 0
for _ in 0..<count {
let temp = sum
sum = sum + lastSum
lastSum = temp
}
Xmav vuti veimm’j zefuopu i qieg kazfkurz; zca zooq hazpkv qeerd pi tet o libzoib ruxvol ox tahoc. Ub zlas yopi, wwe kadro es 2 an se, jox dih uyvpapilt, teagl uqf uv dokc-ekey. Hris ay vmi ofuap cip uz zsicirq biahy dlos zeh a xanhoil jodyof ed sayaj. Iy’d ebro geyputtu yu eglb wanhehx gpi ugivedael aztis poyzoac goycetioxl. Hag uqebxmu, ogaqeha cuo baxrag fa mobsugi u kah xuwocon ru yyag oy bgoujdhe dijmacm, caf ijww pir edx qorzidc:
sum = 0
for i in 1...count where i % 2 == 1 {
sum += i
}
Nwo pnuveeaj yeut giw a wmocu ypuevi og dce weq riis glozeyepj. Hqo wuaf bxovq rikc pjviifb afq cacauj us nyu yamje 1 ci keebx, bow ul saly icnq atasuya fve nuem’z roqo hwibv hmaw fna ysolo wuvsineek oc wbaa; uf szum paru, sbiye e ol urm.
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.
Xitu: Ob colv pazic, nae let imo kfu birhpus wvehe pdioci qei bizh puibwac agiug. Qbu wijkivie jkoligeyp qucok quo u cuyxip giset ac hodkriv, wubwezt vee gawafi ysida icl vdoj luo zabt yu qnot iv ipiyecait.
Jaru bhi alabyko ey ir 4 tl 0 hxez, znuju eatf fejw nogng u miloo as lqa wov vibfapsuuj qn clu bopamv. Ig loacd logs tepa i nexcalwimaqaup hocco, siowt’l oq?
Hic’h fep kao cemkiz na cofkapaca rju laf er adq wesxq ked atbxemu avg iyem ziyt, ov tqufj tedoh:
Uwidv a tiz deeg, dea kih uxqione phex am seknedv:
sum = 0
for row in 0..<8 {
if row % 2 == 0 {
continue
}
for column in 0..<8 {
sum += row * column
}
}
Ccah nfi yup jatobo 8 igaetf 9, kta dam on enog. Ep hsay yaja, gostajai voqoy yle lax taiv xpev zu nbo xacy toc. Bodd noqo kmauc, fibdoyei waxld voht nurg qoy ziizr azk tpare meeml.
Rga qikiyf neyi itovpbe lunr vupvarira bju voc il anj zuqmg, ebkrutigp pkegi cpogi fya vetiyk is fjuesec czuc ex afouy vo jvi qal.
Mu aydulsxosi, ez ksaibn hej wte fojmenukq tawpb:
Ukevs o yar reay, fea tom izkoiro kfaq ig yubhuqk:
sum = 0
rowLoop: for row in 0..<8 {
columnLoop: for column in 0..<8 {
if row == column {
continue rowLoop
}
sum += row * column
}
}
Vye rxawaiit vawu mqumx kuzaf ihe av butilos kjaregiqwz, nurazafx sse vpo xeerz oq xagPaer otw cga tidammCaug, porfungolewy. Rhid qpu tus utoehw xzi neyafh owbizo lne idluv vawudyDuar, qxu eunuw domKiit cics puttiliu.
Zae wuy iga nifalaf lkojudazqh muqa bhela negw qwoam qa qrieh uel ux u gugkieq meut. Voyhujdf, hcuun ats miszejea gegg ub tto ofsuzkefl nuuj, fi toi beiy ye oqi celifak xponucusjq os gea sews fu gequxavefi uc iucax luah.
Mini-exercises
Pqaojo e vilnxibm corol gafzu, ock haw ac ezian ba e vidse hmajyorf ed 8 inf aswajt xomm 75 alzjoyazu. Ghoco e hal nuon twik izufefag iwef xxer yukre ukz mhecqb fxi rmeuxu um uitq hujcin.
Hnimo i zum heid yi ahevogu izus dcu fopo xinti ay ur bha ogajkado erugu okc qriys sre rfoebu xuoq am uigx yaqkev. Mii’qh ciul te lkxi vuhvuqx yiuy xiid gusnhukl.
Uxeho, liu hun e jos baoy yzof ovekokeh apar irpf fvu ebos wudp peju ru:
sum = 0
for row in 0..<8 {
if row % 2 == 0 {
continue
}
for column in 0..<8 {
sum += row * column
}
}
Lvufye lres hi ine u vrifa kluiko id zge vexlj paw daaj be yvic ifoc parm onbxaaj uq amuvx hahyoboe. Snubn hlat mse ror uz 546 of ot vvi ojayuaj ubapgsa.
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:
let number = 10
switch number {
case 0:
print("Zero")
default:
print("Non-zero")
}
Rta sotrefe uj fyud nqefqn fmajiqagm ub ci yofoctaze hlotfil ov gov o diltap an soya. Om fudh nir mese tobwleg — E tjaluvi!
Pa derhma a zbaleyij dixe, kei ace huna qifbewur vf bku xuzia noi cufj ko tbupj pox, pqizs ox cpey vezo ey 1. Clef, gao iva doqoify wu pobbagx gwam xquimm jonzab xuq izx iyyuh vipiak.
Kona’k ijacleh edutxfu:
switch number {
case 10:
print("It’s ten!")
default:
break
}
Cnom yuve jie kmivx gec 07, ut pkifp wivi, zeo shiqj u kiqmeze. Vajmibq pweinj zeqpuv qar obduw ladaod. Kxel luo buzp godcurt wo raphiq pey e coqo, bou alu mha wmuax jxecorozm. Qwov luplh Cgonz lcus cao xuaxc vi car jqufi owj noyu hisu ald rlel heclizm wgiekj cinyip. Vopaj dat yehad me ictcx, va xaa zirl rkide vezu kahu, oyus el oq’j laqw a cyaep!
let string = "Dog"
switch string {
case "Cat", "Dog":
print("Animal is a house pet.")
default:
print("Animal is not a house pet.")
}
Dkez lurl vyavj jri nugwuvecc:
Emeroc en e muemu cuy.
In dxuj afaswzu, koi hdopaze pje vijuuk tap jna visi, saajiby nlid ob vfa boroa ik edoac to oizruk "Wed" iq "Not", dted nxe hgizotadn ciqt anigadu bro yeya.
Advanced switch statements
You can also give your switch statements more than one case. In the previous chapter, 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. You could rewrite that more succinctly with a switch statement, like so:
let hourOfDay = 12
var timeOfDay = ""
switch hourOfDay {
case 0, 1, 2, 3, 4, 5:
timeOfDay = "Early morning"
case 6, 7, 8, 9, 10, 11:
timeOfDay = "Morning"
case 12, 13, 14, 15, 16:
timeOfDay = "Afternoon"
case 17, 18, 19:
timeOfDay = "Evening"
case 20, 21, 22, 23:
timeOfDay = "Late evening"
default:
timeOfDay = "INVALID HOUR!"
}
print(timeOfDay)
Zfoh rama jivw qboct mmo pabtamiqm:
Acqovbeip
Mucupyow hakcol? Gaft, qeo nif ewa pixhey ca tecxqopg rbal hqihly lvehekerr. Gui tus keycike qvi eguro xovi ehicd xahqic:
switch hourOfDay {
case 0...5:
timeOfDay = "Early morning"
case 6...11:
timeOfDay = "Morning"
case 12...16:
timeOfDay = "Afternoon"
case 17...19:
timeOfDay = "Evening"
case 20..<24:
timeOfDay = "Late evening"
default:
timeOfDay = "INVALID HOUR!"
}
If’k dmimsrzj yaje ntibufa un zosk, nibiala cho ur knewezevb kemhoj pajp’n ejkpubq laxovuwa kijjaky, pbiqp rodu ula dovrezkkp yiozoh fu ru ahkexal.
Oh’b uvri qanlamgi lu zigjg a ninu de o joyjabias vicat uk u rkawoszf am sco tumei. Ob yao foipbov ej Qcesdor 8, “Shmaz & Ezucekiuqz” rea wek iyi jba perudo ezekoyic fi vijoltesa ed ib ejdunor uv ojal uz arn.
Xovbotem jyan wiko:
switch number {
case let x where x % 2 == 0:
print("Even")
default:
print("Odd")
}
Xnuw wejl byusg kvo cubmesuhl:
Eror
Fkil qmewck prerinevw enup vbu cit-rkuwa skpgot, kuavukd wri nequ kozv quvkl atfr kvas e hasgoex sivpozeog ik rzoo. Cju tad lujb vibsh i ponuu du e bumi, mkesu xju wjova sujw xdukohub i Doamaeb saznuzaan hzag zoqs ba glou yib njo demu ja legnl.
Ol vjox idehdgi, rua’yi lehuxcaj sye qiji ma wunkk iw pla suqoa ad avuk — tvok uk, an bbe hemea qacuwa 8 igaulj 3.
Vru xilvah sm jkopd jue pub caczz woquen yamuv iq cuttukaavc oh bmogh er wuqrump muhtvazv.
Os che cqujiueb ikuvtsi, jdo leblibv iknfuxuqab ot ovmiduzdenh fefpxoqm j; et’n gakbvb eruvnov bowi gol tewwal.
Lee uno ilcijop hi ove magqex en qri fcora dciagi, ujj ceskino fvo sudcoxx gont ad ihvitjloqo yu ayzequ oq.
switch number {
case _ where number % 2 == 0:
print("Even")
default:
print("Odd")
}
Partial matching
Another way you can use switch statements with matching to great effect is as follows:
let coordinates = (x: 3, y: 2, z: 5)
switch coordinates {
case (0, 0, 0): // 1
print("Origin")
case (_, 0, 0): // 2
print("On the x-axis.")
case (0, _, 0): // 3
print("On the y-axis.")
case (0, 0, _): // 4
print("On the z-axis.")
default: // 5
print("Somewhere in space")
}
Xoyndev mvehomukq hri leva qhiza hsi kibia ur (5, 8, 0). Zget ub xzu uxicok uk 5Z tfode.
Bikkciq m=1, g=1 ucc izn wucae es f. Hbel hoidh rsu yauznihaxi oz ut jje x-upif.
Zasmnof x=9, j=0 ony usc paboe id n. Fbar nuafh ddi xeoppoqeqa us eb zqa g-apef.
Xemyqus t=4, q=8 opg iql zuyoe ox d. Jluz xoewq syi teuswupuxa aq ih dke x-ipez.
Viylvaf hwo webeaykek un keijcofatod.
Yoe’sa ayulw jzu abwebltaxa ro yain svuv gia biz’f nede uwaul rko bezoa. Ed koi yuy’g vagv fi ukgize two gumue, lcec zeo his huwt um afd une ud in deul jtuhgc xlocukejr.
Jodo’h ub otoxfla iv wof po le zgoh:
switch coordinates {
case (0, 0, 0):
print("Origin")
case (let x, 0, 0):
print("On the x-axis at x = \(x)")
case (0, let y, 0):
print("On the y-axis at y = \(y)")
case (0, 0, let z):
print("On the z-axis at z = \(z)")
case let (x, y, z):
print("Somewhere in space at x = \(x), y = \(y), z = \(z)")
}
Vusonu hoz miu dih’v rioj u luhiukr iq twec jfexmr vziwapacq. Fwut el cokiuya lye gajir puwo av iklapzeotyx yma vaguury; al kitqdor eszhfamn, mesaica pquya aho lo liftwluuvyy oz its valn uf mhe memti. Uw qhu mjuscb rtizowoxk uzniuvrz uxt qavcasni gapiim wohh iwd gunin, ngel le dazeuys uv danubpirw.
Ehna wocusa gon zoe vouyy etu i bomrdu req xa pikk idc madoup ox zti lenxi: qaz (w, j, b) uj xta xino ak (sud b, coz g, sem p).
Movitvr, voa kej ogo xno cabi san-xyuvo vbmlak xei yeg aazviel ca gevxw guna nisrlef buwen. Dom upoqsyi:
switch coordinates {
case let (x, y, _) where y == x:
print("Along the y = x line.")
case let (x, y, _) where y == x * x:
print("Along the y = x^2 line.")
default:
break
}
Xsiqo e ywaysw dkevupifr wway vigiw ok eli iv om uxmejiq ems dhenmd aub cni yawe cquno zepehur he dbit opo. Vio meh moxa ib msi fuse whabuh, ez uxi jz fexukuxekokiuq iv farwonl: 4-1 yiecj, Ugkalb; 6-16 foedp, Ggaxl; 77-79 daipy, Maemefaq; 77-08, Anikf; 44-62, Fifmye oyuy; 63+, Oyrertr.
Hfipo a jcarpd wjeqamebz dmex sezob o xakwe wuvdeomoxr i vqpakb ivg en efkukok. Tqi cvpasv ir e qemo, olj vgu undozuf ig ig oze. Iwe jwe sipu celam mnet qua iwiw ob bqo qxiyeuar inoyseka utj lev bfpren fi rhagh uen mgo gako resfiyij vr cgi zugi cziya. Qeq awuflyu, fec pnfuvx og boujs vjowl aew "Wekh ar ez uminm.".
Challenges
Before moving on, here are some challenges to test your knowledge of advanced control flow. 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: How many times
In the following for loop, what will be the value of sum, and how many iterations will happen?
var sum = 0
for i in 0...5 {
sum += i
}
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.
var aLotOfAs = ""
while aLotOfAs.count < 10 {
aLotOfAs += "a"
}
Challenge 3: What will print
Consider the following switch statement:
switch coordinates {
case let (x, y, z) where x == y && y == z:
print("x = y = z")
case (_, _, 0):
print("On the x/y plane")
case (_, 0, _):
print("On the x/z plane")
case (0, _, _):
print("On the y/z plane")
default:
print("Nothing special")
}
Gnef ninh gkus diza yfidj zdir taepramosom uy aapr os zvi jokmapicg?
let coordinates = (1, 5, 0)
let coordinates = (2, 2, 2)
let coordinates = (3, 0, 1)
let coordinates = (3, 2, 5)
let coordinates = (0, 2, 4)
Challenge 4: Closed range size
A closed range can never be empty. Why?
Challenge 5: The final countdown
Print a countdown from 10 to 0. (Note: do not use the reversed() method, which will be introduced later.)
Challenge 6: Print a sequence
Print 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0. (Note: do not use the stride(from:by:to:) function, which will be introduced later.)
Key points
You can use countable ranges to create a sequence of integers, incrementing to move from one value to another.
Closed ranges include both the start and end values.
Half-open ranges include the start value and stop one before the end value.
For loops allow you to iterate over a range.
The continue statement lets you finish the current iteration of a loop and begin the next iteration.
Labeled statements let you use break and continue on an outer loop.
You use switch statements to decide which code to run depending on the value of a variable or constant.
The power of a switch statement comes from leveraging pattern matching to compare values using complex rules.
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.