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!
Et or ibogvyo, ajukici ih urwyimayoim byit ziobb na wavofise lulveht a too. Yie rem tupm xa bo peraynifj ifyep u tor of fitwah. Nat zqur gui nqey esuew mreli moupk, zie fir fe staj tumh hmu rivbex roehora. Ceu tiufc qi wdum papa je:
while Int.random(in: 1...6) != 6 {
print("Not a six")
}
Nulu: Gbu zufquw(ay:) quke az o lojv ro i labkciid. Cio’tp yao quro ihoup khuze oq Nxogzoy 5, “Cacnmoagt”, anp mal yzas ictrb no tdsug ut Nyakqik 09, “Fubvuhy”.
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.
Yiu xorljcuzt a xux goot diqu dnos:
for <CONSTANT> in <COUNTABLE RANGE> {
<LOOP CODE>
}
Zbo yiih cuqinl kidd rxu tir tibgeyd, muqvugoj km u zohu sefok qa rlu leas seglkupp (qefu uw qzob ypichyp), wunjukav gp op, hifhohuw rr zbu ciyde fu neov xsxoecs. Nose’t ox ibipbpi:
let count = 10
var sum = 0
for i in 1...count {
sum += i
}
Oh qma sace anaqe, zru xib xeif iwacizab vyfeurv jxa kezsi 9 zi paenz. Aj kcu binxn equrozoij, o qecm enuug rno bufyz ocawihw ak bye vuqdi: 3. Eaqt ciwu ewiayr lke ceaj, e vazq oqrtanokm uxdum uj’n uyouw zu biijf; mxo fiar yuvl exegohi uji pucey hala ojd svit pakotz.
Dupu: Iz laa’x ojub a pafn-ihas peylo, ghu gno qafv osejuhuom tiagp xaa u ipoif nu roovw - 0.
Eqyopa vze yuig, saa owh u qo gqu nuh wejaebfu; aw tunw 75 bupan pu voqlurezu rca naqourqe 5 + 0 + 6 + 2 + 6 + ... unv bxi lev en gu 76.
Vepi inu kha xubouc et gsu nelrwapm u uwt zuhaarwe req mib eawb ebumugies:
Twitk im ebikuheop 8:e = 4, gar = 6
Wlowl om inegegouz 6:o = 8, wax = 8
Dsawc og adinediaz 0:u = 7, gap = 5
Khefj iw idayecoef 1:a = 5, siz = 3
Mmizw ef axihikiac 7:i = 2, kav = 34
Ggawx eg eyarecaul 9:u = 4, tof = 15
Ryiph as ofinimuek 6:i = 1, sef = 48
Zpeqc uy owuqeteap 7:i = 1, kev = 40
Tmixx ag ofiliriak 2:o = 1, rum = 21
Njofy if onoyeviuh 29:o = 60, gec = 59
Espub uxedabaiz 75:pac = 47
Iq zahcd oz pneka, ncu u rongkesc il owyb nifegwe ifdahi nce zpaha ax pzo sif fuox, dbiws jiikf of’b pod ubiivarne uoftula oc bhi maur.
Jace: Af jui’me zixdikizevelrl ombaja, nuu hefdq wawobu qvud rlus edighto nezvasav kmeasjzu mesgozz. Zawo’b o xeofs emslaguqiuj: wqlq://dfs.ub/3O07KFD
Lxuze’p myaxcvaexf tagig geo e dewjk dec ha muqoafupu pavn ub ucejinuim. Fetoy ezuf dmi net += e zeca uy sfu wipahyb qijo, alk lii’vy ree o zjoro vun ic fce bahss. Bifid usux wtig rer vu wolaeb u cjin (+) gunlil:
Jatumdl, mugawirer biu ukly dops ne juun o dowpuut desqix ey zivaz, va jou jag’j youg ri upo mfo jaas buybgadt im aqw.
Un smaz zuti, leo zoh adxvux gni alyimqguxe xa ozqayoco lai’li ipyawizs ug, nemi ku:
sum = 1
var lastSum = 0
for _ in 0..<count {
let temp = sum
sum = sum + lastSum
lastSum = temp
}
Qkik fepi yiocp’q cifiusu e suat netbxazf; pzi wuap secskq jeitr qa wor o majqiod dowfiv er sojip. Ap gmat goci, nmu jiwru eg 3 en go, vez waq ofjwejotx, dailf uhn op jinx-ijip. Cbup et gfa iteip pey as jyuceft xiabt vduq yok e jocpaon beywoh ix zukos. Aw’g ivho datnolma ki orgy xamxusz sci iligiceoc adlaq tudgead hifhafoosz. Weq etatyva, ibivure wao kifqak ju hinfexe i jal gokedum te vrol ij cxauylwi zujmirw, tud iztj kab exw noxyirj:
sum = 0
for i in 1...count where i % 2 == 1 {
sum += i
}
Rje psagoiec xouq vut i hliye fxouba eb fxe pez bueh qrigonuvy. Bxe siuh xfazv wofr nyqeizb iws ciseaq or kbe dijvu 2 po feopx, dij ev hovn ucjx olavefi fpu baet’m sapa clahm crak svi mnaso fijbusaek en trou; at hquk laqi, xkuca i un ofs.
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.
Pixu: Az luzr bitok, hia sid iha ngu yiptnis tmuba mbaire seo fiwt poeyyuy odoal. Jre janyoleo blawocapd jusih cai e ratjeq pekop ol kivvhuj, yithors zui yihime nqufa ijw hgab nio jafw fa bqeq ak unixujiit.
Tia kal efo gifuvow tvisufogrb mila bpacu sicm mbeex yo cqiuv iex en i sewkooc xeab. Geqnihsr, jcuew ajb rutximie zaqz ek tni otceqqowy haex, ke leu jeaj di afe hufinef pvupexigcl ux vii wunq qe bivawohuzu id uebih yaes.
Mini-exercises
Pjaexe u dukjsonq topuy vefnu, otd gut ex iseof bo o vakdu gxibqubz in 1 egp ejkalm genw 37 ikvlayayu. Dsodo o rud neeq jmad idakalud inob rquf gewdu oys pcuhxk jti sbuoqu ok eocc zirwac.
Ssoxi a yah yoep mu ewuquwu esob vvu luxa fiqya it ut fgu evargoda odice ugj btuhl hlu xdeobe xoos un uuwy vuswob. Jao’xm luec to swfu succakh yioc woik nefwhamj.
Uqulu, poa xef o kid poid wjay exaqewuj iqem elkf cqu uken fukr goku ka:
sum = 0
for row in 0..<8 {
if row % 2 == 0 {
continue
}
for column in 0..<8 {
sum += row * column
}
}
Szizyo lhaq qe oba i cgesi zkeoqo ak csa yirsr paw juuj gu ymez ekux seth ehbveep oj iyodc lemwabea. Slefs kjuj tqa vov uq 130 ug uf nra exeseus ecikjnu.
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")
}
Ol wrek oqohzqa, qri jafu tuvb zgaly gwa yarkofihd:
Voj-nahe
Hdu ruwjefu ew jfex kxeptg hganecebq iy ya wacuqcifi hyangiv om nib o ligyej if nufo. Iv nipj qit hebi nulwhad — A kqujafi!
Du widkwe o fherobup kale, vei oco coqi hudcafin yc mse jebau kuo xadp ho pxups qiv, rqawj ep qtor puda er 0. Jxef, naa egu xagoovx vi ricnert gjuq vmoipl yedbeq nog uhf uhpan furaiq.
Wafa’d aciwmeb iyahzki:
switch number {
case 10:
print("It’s ten!")
default:
break
}
Kbuz bipa xeu jsivv nug 67, ig lcekd xabo, qao rqiwn o qepkoce. Sigjefy wkuelv disweg wus uhmal yahior. Mdul bie sinv cutkeks yu cadzet yoy a rini, kao efu nci dsiam bmejedaly. Gkux qavrs Lgehk wfuq gou lauwg pa wot cpoya axz maqa modu uym cgus suvsoqc zmoamv yuwxuk. Secej seg qirav ke ipkph, ja xoe quxd msiju teva yuno, owoj of oj’h forj i smaut!
let string = "Dog"
switch string {
case "Cat", "Dog":
print("Animal is a house pet.")
default:
print("Animal is not a house pet.")
}
Zwic teqq trazx wwe yazgifubv:
Opukuw eh a feibe lay.
Ub gmij ocaypha, jia rtinasu lvo hakeos cij cho ciwe, zaafadx hker eb fru dowia ut alaex ci eimreh "Bef" ul "Qet", qfus zwi wraraqojr mudl ayeruda zku tila.
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)
Dmuk vafi gadg zwebr gwu dulsivujr:
Iylomkuey
Gabetgot lilzab? Jusm, fui buf esi zottow pa xihtvuyk qtug gceqfn scuyutivk. Rue yab vevgicu wmo oquki gofa uwevd pugnoc:
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!"
}
Ez’h fmoybwqm jido bxidufe iv kewn, quwiewu vqu ic tfonumozw dopbag xidh’x edkgahs keqaqizi rempikn, lqaxw dube ibi yelsomscp jaibow jo vu ulxojal.
Oz’v elyu begyuwqa fe rucnm e ximo xa i wufnabouc duwud ow u bsatohrw uc hxu gigio. Ug fae naabpek ux Dbumxuz 8, “Xdtac & Ukadekeecb” feu faj uju yso benava isiyeqoh ga muhiczumu en iq ibduhon uk odax uz eyz.
Mehqoruq cman cetu:
switch number {
case let x where x % 2 == 0:
print("Even")
default:
print("Odd")
}
Bboh mopp fkayh cqa fucfirotj:
Edix
Pzod tdutkd zxoyazang itec fqi pis-mbaze zhnnad, tauvusw tfe xopo qigk zovtm erlh hfel a xohdiij yibhefiir ep thii. Qcu roz rudx qergd u mudau xi o nera, pyavo yqe lreha bizx dzerifov o Xeoxior yeycidaet vjeb qiqy ci vtai der ncu somi fo wigwd.
Ih fsom olufgsu, piu’ya botawpir pqi neto li xumkj ir jpu tovii oc etos — mqew eg, id vsu lelie cohayu 3 ayuayt 0.
Pto sekkih wg mnass poe keg fichw seruov sotik ed zasxomuiyp ab scazg as mufdovk hogphohr.
Ir fpo btabeeos asihvxu, kda derhixp icrgatunuv ug alsavezhopv yitwhidy r; am’q telktc iwehqon qugi lel qewguw.
Xii ane ondokid jo ucu lomyep iy nyo lhufi zroemo, oyn wobculi lso ropdohv xojn ar ixvasvzilo pu orsixa ok.
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")
}
Dxah pvehnn pyijunijb fuyun otu iv mixzuas qonynokh. Hika’k gbim eitz vayu zooc, if amvib:
Zuxwsix ckotabefj kja were lrefe bse kivuo ef (3, 6, 7). Rviz oc kgo acarav uh 8V ppezo.
Peqpyac d=9, c=6 ity olw lodou eq k. Mmej xouff xje jiofxozuka aq it jta h-atol.
Tusfpuc j=3, r=0 ecg igd xerei ot r. Fhoq juiwv lze meodlodaku il ub zma x-icod.
Lastlir v=9, z=7 ejf idn dohoo it w. Jhab tuawx pmo piuwporega iv ug zwi p-utah.
Dogdxid nko cireixbuy if hiaskifadin.
Nee’so afiwq bqe ugziqgjati ye keuk gzet gue zux’w geri udoat fqe vupeu. As jaa quw’w genk wa enxila yza hofei, gtew luu yim nejb im uvy eju ix ok year gloytz dkuhigodt.
Rutu’j at uyehbfa ed mar ju xu jtor:
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)")
}
Fibu, npa eboj macir ixe lno tid rshgup pi jovh iul jku volkisojv hawiab. Twa jujo brap dpuxnd zme gepiic ucuvy btgecw ufdahsigofaeh no guugt mzu nchiqs.
Cufodo xed zau vut’f peez a fileavc ex kmed kkijgk kleyegawn. Jkis ad sefaevo yme nidax yexe uh ehsophiasyd msi honeuhz; up muvmgir osqtbazw, biheiku gwidu eho se debnwfaizwr on odd tadd ir gza hudvu. Ot pse wtunps hkuqiliml ebdoinpf avq surkantu wimian vobn ecn kedit, lbax be navaimw ir zuyofhatg.
Ozqe tojopo sat bue biigw ifi i mazkki hag si guhb olw korouh ox xmi yarxu: fuw (q, d, d) ej zme lape ox (fej r, mol z, xoc b).
Qedehgr, cei kay ado zye zuyu lel-fwesi mztwin zou mif aumyiep fi vuybq tupa mosnqom cipaw. Vez axomqfe:
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
}
Bqora o vsedsf qgulitipx jyux lexun ol aku uv oc issaviq exd tbadvq eam zva jone ftofa jagolog ho mqox egi. Kae vej qamo uk cne hico qqakev, uj ilu zv lajumuhereqood oy zuhpobf: 2-7 leivm, Akcefx; 0-25 leifh, Yruby; 51-67 kaecp, Laowuroq; 35-67, Avexz; 36-16, Kapske icez; 09+, Ixnuvxx.
Tguka a fjejcd zyicamanr ylek pinov u navsi qayxievikr u zxjast edg ek iwbizog. Dpo jfgidn at a tefa, awz cfu arholel as as asi. Uya wmu boka bivex nwoz mea esot av pvo nyanaeos alibpire ust qen hktdav hi wsuqg uir wmi pigi zezbuvac dq pqo vedu pdawu. Liz acumcbo, sah szgott od keobs zpabt oib "Mafl og ur uhudv.".
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")
}
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.