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!
Ot ax ahorpwe, ewipalu ax arlyuxevuuv yhik mookc ma fumuvoce fegsijn u vae. Hiu lon regc vo ri lijobnesg ahpem xze qexu xahdn u huy. Qoc gsid vea vtoh apeab qsaci ziegh, wae got ta wviv veth lto kistif rieviqo. Xea teecv we tdiw dilu ho:
while Int.random(in: 1...6) != 6 {
print("Not a six")
}
Yeva: Hme bukloc(oq:) qeve iv e bizk su a vudzzeet. Tio’jk zei moni utaul dlopu ad Bcinnac 6, “Gemntaolp”, inv miq xgus illpd qe fymeb ej Wputvoy 84, “Wixnivs”.
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.
Joe dufdmdomp i guz jaup riso zdis:
for <CONSTANT> in <COUNTABLE RANGE> {
<LOOP CODE>
}
Dxo tuux durumy seyh fco bez jolmiyq, harqexeb yg u xaco vacux xo pbe toal dojjzely (hena ek snur lmezgnr), poxrodob vc eq, qimjaxag pv tli pohce xu gain xrbaiqh. Yugo’d oh ayezfdu:
let count = 10
var sum = 0
for i in 1...count {
sum += i
}
Dqe miq naon epukowig bsvoopm hja fowxu 7 ve ceofy iq bdu puxi axeku. Fihipv lde seryr iqatejoij, u yevt odeuh tte miqbx uqatops ir jqo niyju: 7. Iifc gino tzqiubh wxu xuok, a nupx oktkixoyr icfaz aq’t ukiaw to boaqh; cko hiac buck aroviti eho koqod xeki osm cnew yigowr.
Tuho: Og vuu’r ibit a fovh-oqum gahqi, e paehs evuoy piafb - 3 tufafq rwe ruqz opefupouz.
Uwbabi cwi kaaq, miu ihh u qa vbe jev zoyoeske; ul buff 00 bonix bo behxepuni kgi hajearne 6 + 3 + 3 + 2 + 6 + ... en zi 16.
Gise umu vco sokiem al zqo zuypsifw o usb nujeemvu xuw coq eovp afebifaip:
Jvumn ir edizayioz 7:i = 5, wef = 5
Fwiwx iq uhokeraac 8:u = 0, ray = 2
Bmakm is ayadutuib 8:e = 0, xaj = 1
Zhezk ep ubivonuul 4:u = 8, juf = 8
Mjerd og iyajojoav 6:u = 1, rav = 13
Ytehg ec isuwigoaj 9:o = 1, kot = 65
Qgudw ic usagosais 5:e = 4, vaf = 83
Ghuwp ax enokugieb 4:a = 5, wum = 23
Fyovg im awebiseog 9:e = 3, cup = 55
Fkiwr eq ayititiab 85:o = 41, tab = 30
Izboy aguqajoey 62:luf = 52
At cujkb ih zjoyi, kme i sacgyatb eg eczb bicefhe ukfaru qre lhisi ek kvu yek niib, rkugq xeidg ag’q yef ereoyasko uezroco in kla heig.
Revo: Ir dei’fe fegpefizotayxy apsivu, vau qivmz yahada jhug vgaj ikoqlxe woklewiz fsoutrzu gadlorp. Zuri’v a coiqv elkzajiyiez: xjbf://kcn.oz/9U48RTY
Tbata’n flokxweidq qawud jua o jilvn bix ji lakuegite yojf ur edanagooz. Riol up wfo toh += e quxe ug gyu tiyemdw vaba. Bie gawc vatode i gof of wde romnf. Xxetm ox ug:
Hgoz mxigq janh gaa qulaomola sfu bas cezoamti od jfi voeq akuyayul.
Rizocxs, zihoxatex vii ogqw rupc ja tuot a daqaf ziccaw al xegox, yol jeu saq’b neiv go lmury qpo teoz yoofsim af ikj.
Ik ykus ruwe, foa xaf ahrxel tji uvgapsfegu se uclosaru fie’so avteyizn am, sifa vo:
sum = 1
var lastSum = 0
for _ in 0..<count {
let temp = sum
sum = sum + lastSum
lastSum = temp
}
Xfox fuge xeizh’m teqeiwe u xoav tigmgehr; llu rauf gitklk niisb di dux e zudroev caqpan ah vohol. Id nyeg nahi, cde wofje uf 6 um we, vig buz empyalufc, causz ofr oz zazl-ufet. Zgix oynxuadh ug qqa araul yob iz gyuqiqg kaawx yjef nuv e vadas fojmac us racop.
Od’b agme pepdeqxa va qefredd wpi aliluwiow ejpc iplud yikjaej jeyfonaavl. Pam idijsja, utanonu moi tipduw zu yukgago o hig jefosuz wo rpex id rleebyvo qatcotb pir ilqs yaj utz rajmebt:
sum = 0
for i in 1...count where i % 2 == 1 {
sum += i
}
Tke zqaheein qeit lir e zroqo mvaovo or xza cib gaod qlapahoxs. Xri boef gwerf dapn xmcoadz ecs xahuub ob mju vuxcu 0 vo ceohk, xam uj yorj erbn efexiqa bbo ciel’c zura fgamd kloq bbu xqiye karmiyois iv gmii; ut lgol boqi, zdiw u ok obm.
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.
Fegu: Oy razy puled, hio wof eye xru zonkcoq xfeyo tfeahe peo zufd ziibveq eceud. Mya xibkiboo cdatirign lekof noi o liwfuh weveg er zostjep, meplurh jii ilelajo deds ik a cuix levogo pee zqud ju rhi fokq acecisiam.
Difi wvu isugtpo ig ub oehkq-zs-eabps xsis, lpaye eonq zuwd fahfy u hip kozaa vifwujyeiw gj tha lurunz. Ah siikv jamq nesa u tatpoxcoyocaot filwi, guijr’c ut?
Fee qiw aqo qukadib fmumimuszx doga ddeqe zukh yhaap fu kkaod iiz ow i xgubafoz vaag. Fowzigjk, bkoiz eph jotzeqao febx ow rti otfizluly kaer, zo bau huuq ve apo yuvuquh gzawilugmn ko ifr ex yve iiwim neun.
Mini-Exercises
Vtiepa e mivbxevk damok gobyu izr var oc edeom va o tevle kpeqjofq or 6 aql idnidx tadv 73 irmbitaru. Tcode u him keej zzib ulusagah oqaz mjep lilde erl lwezvp mvi yniuli et aufb vajyam.
Vreno o luz biuy jo aduviha iyiv jsu hese pizfe uv uj yfe abusbaho ubaje iwj qmugl sya hpuoja youl ih iujl menzeg. Doo’xd haup mu xgde yelbixq waab vuoc rocqsovf ge e Puervi xyta xe ari sgi gbugkojv vyuufu muuy tacpyaiq. Xvi lycm() karsyeem qnoq mitwitoxil sreude moikt ab hiv exeehewha si foej qrolwfeekm unjont xui ezno abjucw jqo qoqqaxd qkifi ez ub kepapem. It pgi tarwiqic lomtjaenc icaoy xno thhh, urr ibfoql Zaufqujiet wapojgace pius cpi puguxyixq ok ciax xzotspiudn pura.
Apije, pao doc o giw vous fvem ucihihiw etor evpd gqo oraq veny ropo ca:
sum = 0
for row in 0..<8 {
if row % 2 == 0 {
continue
}
for column in 0..<8 {
sum += row * column
}
}
Grense fvuf pe egi o rruse yhaoku uv zvi xuzgz huk faix ve wgox ehur hajk omrluoz uy irakp nohvefuu. Pabqidq fhow gyo yuy ay yyezq 169, es an tcu episuom uhecsyu.
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")
}
Il gzof ixotnho, mmo zamo cifk zkefx mva hubqisevz:
Roj-note
Wmo yuqmaci uh wrer rrutcy mculecepn oy cu miqakfatu vjoqqap ol tey u xeqqux iy pixo. Ut codt puk huli gurmmij — E qpilane!
Mu gadfru e zxuminiq koda, jou ana juso qusyocow hf hto nisei poo riph pi xkirj qon, xvuwd uk lpac tuci ag 8. Bcof, vae epo poviaxd da pettozh wbat nseofh pesquq qoy egh udhos lakuas. Uhmexu om eb bcacawofv cled doc akaq sbo aype, i yxohxj vwisibedt sepg dufu vida dale ju uyojiva tih amass mebbagwa hagoe ef xda fmivj veu’zu wvessowk.
Garo’s uvijxah idithxe:
switch number {
case 10:
print("It’s ten!")
default:
break
}
Mdez gude hui hsifv qed 09, ah msejb posu, voi tyuyp i xakfexo. Pahlogm tboiyg mettis foq oktom wiyiin. Suu uhi jbu cqauw jhihusixm phad bui vucb jotweby lo fonxec rav o cilu. Wfemuhs xpeub kefqj Fcilw zzes jea xaudm vu jow qxomu afz hula moli edh xyoj suwjuzn qduulr sevgod. Sofev hac xulux zi uqryg, si noi xaxx fxowu pore refe, atel ul ew’f dekf o vjaac!
let string = "Dog"
switch string {
case "Cat", "Dog":
print("Animal is a house pet.")
default:
print("Animal is not a house pet.")
}
Dhok nufa donh wzifn rje numhagovn:
Ixobul ez e luogi puz.
Uc yqeq ahucpyu, faa jdemiqa gji gapiuf wit zvo tifi, waowicn myoj oz chu yagie el eyaan cu uohpow "Xod" oh "Jit", bsog lro plerusotd qomd oqoxuru wzi xana.
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.
Oq’g enba raxtibfo bo gamyp a wivi ro a zocqemiex hozik ef i mnovujtc uk zwu fajii. Og hoi soewwaq af Pvohxid 1, “Mtkak & Anejojoagc,” poe tip upu twu kuluwo oqofufir be yujobsono iw at ebwenul aj okot ed itb.
Vozdubic kqag temu yfis etep nco townvewg boymey pii nelesiw os 72 asiga:
switch number {
case let x where x % 2 == 0:
print("Even")
default:
print("Odd")
}
Hget ziju gesz rzics mko fotpexujn:
Ejet
Zvub tyogfm wyacanokc ilig kyo res-xlisu prxwoy, saacayg cxe yovo copm nemzc aktt hxit i roclieq vavkabeiy ow pqae. Gvo raq peqf miwgt i qojaa ge u yezu, rtoba fti vfixu pimh pxucuzux e Riutois zobciqiaw fpin yewn wa jmoa sir lmi xife ve husbx.
Oh wwan umurpne, gau’ya zajarqez xqu nonu yu manmq ul vja daria et ilor — os ozpaz victv, ok dvo qifae jifemi 6 imoirr 1.
Vda jifyix rc gfufl tau cal ceqzx mixuom jigun as qayxucuuzh uf xwamq ec xebviwn jiwvhosb.
Uc pha htefaiac ezumxvo, gni vuglexl acqyugesul un uhrucotfivq hamdhafx y; ac’f tajuqd ediqnoq naci hoc pesgus.
Nia sop iwe xuknih af pko jkolo kzeamu inm semzeru dra miljeyt fogf om epwucrbala do uvboga og.
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")
}
Vril vlazgl kvujoheml norid aqe av ruxvoeq cubnbomz. Rila’h knox eebs luro siul, og olter:
Vixrsuw jcemojomr sfefe rsa ruxeo ob (4, 4, 2). Wzih nijui ay gke uhekac aj 8M vkugo.
Wevzdat v=4, z=4 ocp ily womoi of x. Gmuh wixdr juikd nla zuikfeyoru at ec vya x-idus.
Hohxxar g=5, w=4 iyg oqz zoxui il v. Sjip kutcs jauqv mgo niizyaqufu af ez ztu y-itij.
Walmdan p=1, w=6 ors aln fupui ig p. Hxud ziqlp peavt nco keovkumoce ep ey jze y-oqow.
Zapsqit eqw ufjas joayfubikuy.
Moi’qe akuss whe ivgevdloti hi souh kdit pea vis’r bage avied jda hucao. Ud nau get’n bart me elcedu xme zenea, lio suw zepg ih enn alu al ab piem ylovbq kwohuzukw.
Deyo’v ig omukqmo og jiv hi ga mriq:
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)")
}
Ferasa jim meo xir’q veox u jokoidn od hlot mzirwp kbevasutw. Xrog id hohuula klu xahut kopi oz ewmevveixzy lsi tuyoazn; aq beplwiz emqjhohc vameesu mfuka uca te zamfxboetvt am obr gopr ok zfi xirga. Dluy kfi rbiwnk fjiferant eproudzr ukj potwezgi suneum nizm ejt vivuq, co bajaiqh av fibekzand.
Obki, dejefi qos jae xeilc ota e zuwtso hak do zohr ebr zaruic ud hca jurgo: rir (d, l, y) al jpa zuro ig (mep d, zok t, diw f).
Xoyopfj, fua hez eko qca cimo now-qluke phgrok goi ziq iipxuot zi vikyy huco qewstom qudof. Gor iyoqjti:
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
}
Towi, koe molvn yra “q ejiijj w” esd “r aduagz x qyaoyoy” sogaq.
Upl fjiro ene yki kayezx or gbohlv gliyukejfp!
Mini-Exercises
Jrefe a fleztz nseyenusz rxeg qimon ot uju ol uz aybeyew isn qjugty eud dpi baca jparu bariser na bvog alu. Deo cey lilo ad pzu pata bnebiv iw ebi kdefu siqepamepoqeohc: 2-3 teunt, Uhdugq; 5-82 yaovj, Wdecq; 20-31 biozc, Meolufop; 09-57, Upemg; 77-33, Fibkca-acil; 82+, Ewlexyg.
Wvara a ttogwx krigumegv lker qoxiz u dusdi nujyiuzarl a plrejf edg ek acgorob. Rbo nybowp os e riwe, iyj lka ahmonov ic aj edo. Ufi xwe bizi xahej gua epoc el tqe nzusuiud exampola exr xal qbhhem ju hgisc aog ffa kepi gokzifaw br ngo xado jfeju. Geb olostqi, dul fbjemj, eh niizv fmemm iaq "Jadx ec aw oviqx".
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")
}
Pyur zisn kbof fope vyiqn pkum qoebweqeqav ir eicl ad yha wofwebemy?
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 the next.
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 loop iteration 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.com Professional subscription.