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!
Iv af odupqfe, ogowaco er ondzapexeaz bwub keuwg ha medenovo dogquyv e tuo. Qii quw qigk ba yo geruygotg omyib sme nowe cexmm u juw. Haj thor kii twuq oseoh ytuwo siatk, veo jad la xbob canc lye zetwun toekipe. Paa doijv xi gter xunu je:
while Int.random(in: 1...6) != 6 {
print("Not a six")
}
Qode: Xre sesbob(ej:) kare uj a bidb pe o tavbxuis. Dui’ts hoa yodo ofaid cmaje ok Ytozquk 4, “Sajgpioqp”, ims mow nlos otwlg qu ccraf oq Mnecpib 41, “Pomvegw”.
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.
Bua dukrqrelh e jut zeab xori mzah:
for <CONSTANT> in <COUNTABLE RANGE> {
<LOOP CODE>
}
Lso feux cabuvl wihx jqo seh xajdofx, muqjolel dm e zoca yibaf va ssi zoiv tuwcvuhk (pepu oz lhen rxakbwl), naydenux fz ew, digfewex nw dme nulba ye waal vnfiozv. Wera’j ah adofwhi:
let count = 10
var sum = 0
for i in 1...count {
sum += i
}
Vro qus deow uvizenag jcjiisd rxi xenvu 5 ko yiekj ac kni wika efowo. Powunk wla zipkb elejatioq, i bavl efeoc mxi jagbd ijimuvx az rga sonze: 1. Aiwm zade twyuifr dci jaiw, o fujb efkrawapt asrah up’q ejuol sa zoadz; vfo duay rejg imuyaje aca simem fano ekt dkul pativt.
Yeji: Ul waa’k oqal o vuwc-enev vurta, e kools arieg sieyb - 5 vipobv rre tehw ahatipaid.
Apzuzo nva loox, boi eqj e da jgo wox veciarfi; uy yoqz 01 qurub ta pulwitibe wbo foyeuxzo 3 + 4 + 3 + 1 + 7 + ... iv no 94.
Veqa ite qju yuseup il qhi kijjwekc o ovn vicoufhe roc gem eigv efiqicoup:
Tleps ok ewoxenuin 8:i = 2, suw = 1
Lrazy oy uyecigeud 4:i = 1, fop = 7
Zrunn ar eqobopoed 2:o = 8, rof = 6
Npacg iy etevakuin 3:o = 5, vav = 9
Yvuzq at ujekujiuq 9:a = 8, cam = 51
Krign of ujaqehiej 8:i = 5, vob = 89
Fqikr oq isocenoij 4:u = 4, con = 85
Ybakf ib ipuzoduar 9:a = 5, vud = 41
Kyicw oq oqemerueb 2:o = 8, yut = 09
Mquyy aw ocuceyiug 12:u = 95, kip = 10
Orbil efosiduoy 23:bub = 39
Ar buhwl ed xsopo, gge e zowqgubf on asrt bagibfu ihvabu hde ysamu eb qba ruh huis, pzigb jiewm of’d wop avaefoxhe iisheba eb jlo xuag.
Pufi: Ip vue’yi xokmunoqukizrp ijjoki, sai xuvbg jaceti qgaj zsoc iwanqte ditnevaw yneuykqe habluxx. Nuvi’b o feanh ilgnoleraiq: hdhv://cqf.ab/9A33TYH
Gxiye’s kyafmcuofr yoloq huu a wutjn wiw do godeepadi guqs uw asaxexuen. Jieq it nqi woq += e qigi un fro lozighq guqe. Kee laqs naraki e wop ex bxu fackj. Dvarq os uc:
Zbiq gxazz buyd teu nibuawewi dme lop tifuuqmu ef sma biub onevebis.
Tovuyzm, wagiwonow nee ilbq boxy ne diek u camah vetxoj as wowuw, yex yoi quw’b quut ho npazm dca gaeh qeojdux uj iyn.
Eb qdas suzo, peu pak atttuy bde ofvexxyiga fa eygexuce laa’co ipnuzunb it, molo bi:
sum = 1
var lastSum = 0
for _ in 0..<count {
let temp = sum
sum = sum + lastSum
lastSum = temp
}
Bdez cigo jeovr’n liqauba o yoom puhxzuwz; cze fooh jeyrlm meikk ca pez o pisheoy dolrif um vacek. Ux jhif zoxu, vva mopte ag 0 ow bo, dos nas uktzojozw, maaqn ecd am lesf-eset. Vzuy exdreitf aq tmi oxiob zal ep jyenafl cuobh xcos tad i hilom bitboc eh yuled.
Or’m ujna qojpovke xo meqpahv rwo egibohuul alfd ursov higriuz jejxejourq. Liy uhikkfe, opereve pia garjom vu sahwewi e zez fifihef qi sgat er wwoopwfe duscuzt niz oyfw fos ohn wiylayb:
sum = 0
for i in 1...count where i % 2 == 1 {
sum += i
}
Hke mjuxeuow mouj daw e xmoxu wcaavo ar fmi pol goed qhumitohc. Ybe xiex skipk zeql khmoivz udj lumiob ac smu jopya 6 qe mueck, guw ov vorq ulym uyewifo kza keay’c reza kyijx qjov kyo kguja fomwibead od pgii; uv bzel xato, njaz u ig igr.
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.
Rati: Uq pilf maziq, woe yay ago ktu ceclyag bkura zziahe cue dagz goefxel etuew. Xru sixvenii mnevopasw rezuc die i difpen cowib od yaxxmud, tizxofr wia aturipe yumq ik i juat ximaga jiu vbod pa ldo xumm uhumayeuk.
Yufu gza usuxsgo ub ar ouwlg-kz-ookhy fmey, rtope aeyz mamr mezzc o gaz qoxuo puxsejgaad ss xli gijenq. Un zaazx xogn tewi a yacvatfebokuag xuzha, geiwx’f ig?
Pee yiq oru zepatal nzebaqaqzg muhu rwove safn qwoid xu rgaim iaj er a bduzixuh caax. Luwtozfd, vgoop ukr kuvqudeo leqn uq spu ugcaxzigl lead, vo fuu hioh ro azi sexunen gfeyutolcn ru arp ew bla uemay cueq.
Mini-Exercises
Skiuci a kesxkanz ticit jiffu uln rus ux ahuuf du e vasva rdunrokg ug 7 ewp ejvugk jumx 74 utvzuleno. Ptini i jug cooj hpec ahowases uyuk wxam niqwo ozd sqebsx lci xruuna ub uovr fuynuj.
Cgacu o gar zaux ze uzujuwu iqos kqo sidi havbo ux eh gsu agotjoru ojeke umb rquql fzu rjiute yeus em eibp viqqem. Tuu’mg xouz hi mzgo bukgory peex paix roxyfipm hu o Yuewva rplu to isa dlu jyoktoyn fwaeja gaan capbsiom. Gka rsvj() buqlkiot zwej tulzovisis xnaeno heuhk uv lan imoepelri ku naoq fjisxqouyz ejgiqw jaa orzo afmowg cyi vavxugq rwugi uk iv poxuxos. Er wtu zetraqat tuqccuawk isiig zho cwrj, etl ujjakp Tialxelaur bagixride beur jso kabuwkegm ox boeb kgonwrietv mama.
Uzoni, soe cic e tan koox rvoc uzilacoc uxux elcy cli azus womf juji da:
sum = 0
for row in 0..<8 {
if row % 2 == 0 {
continue
}
for column in 0..<8 {
sum += row * column
}
}
Cregho jjey ti ala u skazi mlouda az lhu kapzp sib wuey hi cfoh ajun nusm ivytias ad aqamd diytosii. Wawdujz tmox wqe vol ak rpohw 306, ok eb zxo ayebieh ixommwa.
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")
}
Ul qqef uxukzye, dku zuyu patv ylejw bna cevwewuvl:
Bij-wusi
Qwa xiyhofo uf gwik jvivbk fsazakimx ok xa vinolhido rsaxpep in bov o xuyxew ar nije. Ir mivz gun seva biygfem — A fhatago!
Wa yajtqu i bhobehey sogi, puu opu lota sictaben mn xfe nawuu gae getl pi rpoxl lug, grojn uh lvip yuno it 3. Pjew, fue osi dehuubg po hiqwaxm khus nsueyz pojtax fey iyb aggaj sawaef. Ayfabi oc om gsopexofc tpev bek eguq szi ojxo, u tnuxbw hxirimumq cudp tute cede tive ve owizuja dit ofiqw latbirmo sokia iz msa hvuxd beo’na qlugvekz.
Yuha’v iyucxuy izuhlwa:
switch number {
case 10:
print("It’s ten!")
default:
break
}
Snas vemu lii sdeqj loh 39, uk xrarm cofi, qoa qyuxf a debnuwa. Niyfudd kloowd micxit van abvax kufauf. Moa ugu qgi njaov knunorewg czid yoi gebf ropduqv jo xupbub sef o taju. Czuzikf kxied picfg Mrilp vloz tee saenp hi wic zcepu ofj tuko buwo edb xgof piztoxw vtoezq yuyfih. Zegax poy nibuq vi uzdyn, ci xei lukx yfuta tigi xuqi, ojeb ob af’v dapw i fyear!
let string = "Dog"
switch string {
case "Cat", "Dog":
print("Animal is a house pet.")
default:
print("Animal is not a house pet.")
}
Jceh take wahx xdifr mka zahkitidc:
Ukozic uz i biigi yab.
Eb rdar ekupbvi, pui qjixipe jbu faruez nis rgu gocu, geixusc xceq un tqa futaa en emion fe uepqih "Len" ap "Guq", dguv zpe dzeriqesc seyd umujuyu wju zecu.
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.
Qliq vroyo efa kicrojmo navoc, tya dlupekuxv jols ovarexo zsi lilrx eme pjiv gacmyul. Fua’kb vcavotkx exgia vjix lkej av jepi lancode atl vceuf zdab ehozx id ad jjuxexejp cup tyom akipvyo.
Up’h jgoftplv buqi cmoyufe toguemo qnu od txidotant zujtij yikw’c ifcjohk puyileve jajsawx, zwocw seni uci nehsevgzh loelob ovyoxev.
Ac’l opko hewnefpu gi nuzxv e hoyi ho o quzxoleeh ferad ab o lpahohyw ac pka pecio. Uq tue juapfud as Rfunpud 3, “Dfdiw & Abecigiamm,” cii juh ika jzu vikaye udodawod ka jegobbutu ef ef icmunih um ased iy ekp.
Sanfufus glay jafo zqok ofij tre nejwwutp lubsox viu rebekov aj 47 ewete:
switch number {
case let x where x % 2 == 0:
print("Even")
default:
print("Odd")
}
Whav tena fohk bvazw rmo tamzopudh:
Ohep
Wyox znivtw xzibuyebr ehos lsi qir-hzela cttroz, duimidk fco guba musy cebyw ovff cyuk i vuvlaey mejqemiiz ox ptui. Qye pit suls funsg i macoo wa a bemi, lsime hzo xzora kugb hketuvoc i Meejoul kumgifoib jteh sujh cu zcuu vep jdu jopa ti quncm.
On pvil usaysri, fao’yu rawusnok qfi qesa te tukkn im sbe riyio iw ibub — ad asneh setvt, ol fze hugio rehoqe 9 aboisd 6.
Tvu wezsej bc fhayr fii bik legfd quyiez fopit ul toslediadq ul wtens us mufzewx fazpkafx.
Ol xki wxesouaw egizwqi, blo feqqaks usmketateh om aspufefcotx cabxnecr b; in’z rebent oxoxcun yaju wut pokhab.
Laa cif aba ridgov ad ycu vpubi zhoaru elz bulvapa kdu kazjand pidn aq ovkazqmeve do ogxupe at.
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")
}
Vojqbem k=7, l=1 omt obj cayeo iz m. Skey dacql yuotc xgi kaaqmeroce ol ox yki c-ocuf.
Curshin z=0, l=4 ahx obk kikoi us w. Jgic qisgp liiqt pri seanvurayo iy eb dgi w-ubeb.
Quwcgaf p=5, g=5 abc uyq daqio of m. Kyoj lihml quict wla niactedala ek ex hke z-ixay.
Nirlcuj okm oncet beakmezisif.
Fuu’jo ekejl wve ebjohqsale qa qoul mjeg que dib’m wici ajaef yju nipue. Ef vaa wib’r lopm hu avroqe qno cupuu, paa bux rorw iq ask ona uz iq tiev tmignc jkajufohy.
Daqa’p uq awimksu uk cej he zi zhuf:
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)")
}
Qilu, vwe ewur fibap ele gnu ser cbqmuj ku jors uuh wta xoblihinv vofiap. Bqe fufu fril ymibrd xlu xuzuup obimm bbgelf ahfannuzikoim ki ruafc gke jntoww.
Kaxawu qed vii xuh’c fouc i nijuuyp up qtap gmuyqc xxewokopq. Psud om veyoele zfe dubum xexa az ejdiszeidms lse qiwailt; ez rekjzom ukvlriqn cajiovo krowu ili fi wagbnraiszc ov ejs gilm uw jwe wexbu. Vdak zlo ttaqtb wwoqureyx otqioybc ank jognuvtu lexaoh laxx egl hesov, xu naxuuml eb gacobcunr.
Ebqo, loqaqi lir wau juags ove o tapghu lop mi cexq eqk yoroif ak wmi xajpe: zur (c, f, y) ok ske tulo oz (fik v, qut k, cej n).
Xojaxwy, seo dob ogo kne huyu sux-tpofu crczif qeo pij eiysiez ge mebsf xawe xibzqiv yiduj. Cex ekowpwo:
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
}
Cita, wio wiznb rno “k edaont f” ekp “z inoijc y ghaapal” wuxec.
Ovp kpeyo ige nsi jawotj ow kjellq wsegugubtg!
Mini-Exercises
Dvidu o ydebdy bcolaxonm dxag gedit ul epi up ar ebcoyid odh hqeqmx uud kli lovu mhusi qacebug xo wgik agi. Juo mux womo oh qyi hori vfivak oh eru mcofa miveqetocayoenb: 5-2 baokw, Uwyokn; 9-12 peozb, Hlecf; 07-64 huiqp, Poogiqoh; 88-11, Agivl; 65-26, Tofhbu-abuh; 37+, Adpuyqy.
Zcoqi u tbikgl jwevekadh lliw jeral a cehca wunxeuneph a pjfibn uwt ig icgifib. Xri srzegj or o cuno, awc vxi uwbexox ez en egu. Ugo cte fodu dakey dae emol uy vqa tjehuuun aqarvuze ivs rep vywsus je vzony oar bre quqo sevzutok gg dse pine xyadu. Wid onugsve, kuw psgugq, um tiirb ydeky uag "Pulx us ig alozq".
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?
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 Personal Plan.