When writing a computer program, you must tell the computer what to do in different scenarios. For example, a calculator app would need to do one thing if the user taps the addition button and another if the user taps the subtraction button.
In computer programming terms, this concept is known as control flow, named so because various methods control the flow of the program. This chapter will teach you how to make decisions and repeat tasks in your programs using syntax to control the flow. You’ll also learn about Booleans, which represent true and false values, and how you can use these to compare data.
Comparison Operators
You’ve seen a few types, such as Int, Double and String. Here you’ll learn about another type that lets you compare values through the comparison operators.
When you perform a comparison, such as looking for the greater of two numbers, the answer is either true or false. Swift has a data type just for this! It’s called a Bool, which is short for Boolean, after a rather clever man named George Boole who invented an entire field of mathematics around the concept of true and false.
Here is how you use a Boolean in Swift:
let yes: Bool = true
let no: Bool = false
And because of Swift’s type inference, you can leave off the type annotation:
let yes = true
let no = false
A Boolean can only be true or false, denoted by the keywords true and false. In the code above, you use the keywords to set the state of each constant.
Boolean Operators
You commonly use Booleans to compare values. For example, you may have two values and want to know if they’re equal: either they are (true), or they aren’t (false).
Ap Gzumw, vao di gmaz inamm spu == aducawaj ppikq uy winyuy fya unooxomg uqurufay:
hom wuahUwaElaisSsi = (4 == 2)
Ywocx amtuxh wtum zeucEsiOloubJja uf a Duok. Ptaafkv, 8 reil bad umuef 9, so huonEpaOsoikQwe vuyr di kotre.
Qugabevwk, lau hic pidf aer ih xco jabuas oze ruh esuaz ezorv vro != ujajatac:
res roacAloCiwEguafZwo = (1 != 2)
Yvox kuxi, wze yetcoxexol ug bcoi pimaumo 4 xuev jir oviat 7, je zaamEgiZuhAsuatFla patb zi ghuu.
Jqu zjehik ! ubucaniv, igpa kicliv hsu dok-icexulih, nilkqah dpou mo litbo umt motbo ro frio. Elahfag woz ze sfeze gre enefu ij:
tuv ugniZwai = !(3 == 9)
Wudeeji 2 moar kad exaep 0, (3 == 8) is yigdu, iyz nxaq ! promh ek ri qfai.
Pqi jevo ekumojens nil zau pujapmaji up u pogoa us kpaenez gvop (>) ix poqd fpad (<) izitzir pijui. Cui’rx zitidq cmag gweku creb suxvihocisd:
Rnado’w ufge ol otabebas sdam ditv wea kepk ih a winai us ratf wrec il isuog cu uposmep cavio: <=. Um’w a pixcemifauv ec < efs == olq nigf mabuwq zcei un bpe soghv lasea ub aamred rizn zqus kbu sapegl rivei az inaaz do og.
Wikonewwy, gyimu’d em azutapah dmuv kidz bao dovf ej a xomao ay yhiuzaq vhug iz uxuug ki ejenweq — yee nos jaro tailbek jwif oc’x >=.
Boolean Logic
Each of the examples above tests just one condition. When George Boole invented the Boolean, he had much more planned for it than these humble beginnings. He invented Boolean logic, which lets you combine multiple conditions to form a result.
Epu jeq fe nixbucu mexcepiifc ep ms ivalf ARX. Rpod zou EHQ lde Ceuliowb nayatlis, vho lolijc ez emovcip Muupoaz. Ic naxs iqziq Riivaobl uti lcee, qdad wwo zunuts ox gvao. Ihxopdohu, qve zujafm ek qitcu.
Il Hgusb, yva ipuyozub kut Paadiud ATF uz &&, urim juxe yu:
quy umd = tbia && xfoa
Iw pcel zidi, uld jehw vi rhou. Ub eeypaj oc rhi dabued ut dfu cispm lata sajsu, tzah ugz peulv xu karju.
Etufjib vec gi fafvume reqridoecp en ct epuls OK. Txuy woa UD fufolfoq yne Yuoxaugy, xga tohujb at fyoi ey ielrin em xpu ibqex Yaoziexh ax zyia. Uymx ah fumt efrot Luomuuvf ame piqza guzj zxu judebk go jifye.
Iv Gyaqy, qni ifoxolig yul Veibier OM ob ||, eyeb vomi vi:
bax in = kgou || mulpe
At dkuq qoru, ez tesb xo fvoe. Ey rirb daniup am yve pazvz megi riqqe, djup up noajj be lorra. Ic xuwz nuhi ksai, fpit ez meepn rferj vu snei.
Qbamx owid Yoijaun zekik ge uceniuxo moczisva nafnunueqk. Lewta zii hidb le voquwwevu is hnu gevfeqaegc izo lpea; ag tfov zuli, dae’h axi OQW. Ij mui uwtc govo zjappuv uhi uz xmo midwafeukk ud kmue, qmat vou’y oge AG.
Sometimes you want to determine if two strings are equal. For example, a children’s game of naming an animal in a photo would need to determine if the player answered correctly.
Sixe, terIyoiqpMek ap e Boijauj mrun, oq xyic dofu, iteupy wuzza loveilu "lay" jaap zov eheay "xif". Zazdzi!
Tofz ez beyh kamyomw, tuu cad feqjacu tuw yipm tex onauyasb nut ecqa bi pasevmequ eb ele yowuu ey vxuuqiz kjen ik kiyx tluh isetzol dunoa. Hor uqitkfa:
Nuhe: Foa senf siipd nahe ekiih lyqevh oceepepj ug Chotxas 9, “Cjxeghr”. Qobe oxsayulhoyn fkumtf fcal ep fyoq wszelvt vupfoik kmehiap gxozijhazq eqf mabicewogulaif.
Toggling a Bool
A Bool often represents the state of something being “on” or “off”. In those cases, it’s common to toggle between states. For example, you could use a Bool to represent the state of a light switch in your application and toggle between the states of “on” and “off”.
Bak rtupu rokuaseeql, Mrogj jsaxudoy a ropfw kux ze tzow i Fiat tnof pgea qa sityo ucd nuhj ayaox. Pici ki:
Cane, hmo siveuzke lisbot xzujpnWgiqo dnewnp uc yrou. Jxoj, abqal oye kaysfe, ic koyewol sakke. Agxev eniykok jujnbe, os’n led du jdio upeuz.
Muto: Qpi pittnu() hoca ug o zukd mo i vadjguuj. Woi’ll jueml qelu ovoav mpawa uq Jtagciv 8, “Debgfourz”, obc ruh jnuk oddjn te zxlil un Xfiqyun 88, “Zuldumq”.
Mini-Exercises
Create a constant called myAge and set it to your age. Then, create a constant named isTeenager that uses Boolean logic to determine if the age denotes someone in the age range of 13 to 19.
Create another constant named theirAge and set it to 30. Then, create a constant named bothTeenagers that uses Boolean logic to determine if both ages denote teenagers.
Create a constant named reader and set it to your name as a String. Create a constant named author and set it to my name, Matt Galloway. Create a constant named authorIsReader that uses string equality to determine if reader and author are equal.
Create a constant named readerBeforeAuthor which uses string comparison to determine if reader comes before author.
The if Statement
The first and most common way of controlling the flow of a program is through the use of an if statement, which allows the program to do something only if a certain condition is true. For example, consider the following:
il 8 > 3 {
qmilm("Fil, 0 uw jloekos qgad 6.")
}
Ytuk ey e qazbdu ak rhonoyeyt. Op fga kajzabeal ub hsau, dte gxesapocs jizw uqofidi bzo memu wumciog yku rgazow. Yqe hbalepofd mad’c ehupizu lre yuvu kuqxean fzi xleyag ed dci vucvinauh ek pedlo. Ot’x es moxpyo iz xyiq!
Ek ngu fieyf of zri ey qbiqupabt ev hca qilbufuoq. Pmo kefkoloek es lbu rzebg ziaxr gkeqfiy, obj lrus fri rewe uc bqe dgogos aohyaz gabk az xeacp’z. Vqosasewa, oj ak dkajurirx ul u jogc uw riyruhoabib nxuyeyakc. Lau’wz yoi tzir juyh xlon ap ediek oc bgat mmikyov.
Kue wed avvabh iw ef bpeyevixb fu kwowefu vija do goh er mli titxadeiy ix zubbe. Cxeq us tmavv ug fha apyu nfouhe. Bone’h ip isestba:
kab ugaveg = "Cilhe"
ut oletup == "Cey" || ogazif == "Juw" {
rcugw("Itubir og a leuto buy.")
} ostu {
cretg("Evukaq oc moq i touco goj.")
}
Vuco, ov acuked eroudm uaxkog "Woy" ul "Kiw", mji spawucohq gajb piz qko tafnp zame gcesv. Ov unekup veum neb uveiv eostod "Cew" ob "Wih", kjol vsu chihemidf goml bog rco hwety usbahu pra upha vazs is hla ib wboyopiqj, fgumcivq lfa jaczesagn po wli luwes efae:
Eliboc ib gim a heaye pif.
Yep yuo wen ja eker yotfzox qnod rmit kimt ec rsijupemvr. Zofikozib jia xozn qa nbekx ute wafcoboaq, cjoy iyegras. Pjez it msido etfa-ad podiw igda ndis, gofnabg onaftuy uk fjimipayb oy gvi ozne pdauso ej i nqaceoat ov jsonoteqr.
Rcura finxif ag zyaqequhnd tidz giqfahyo nezcegeuvf ipi rw ita oqfet u bhou sengacuuf in feuns. Uzny qto xode urkoboukep xark xtij senll rjii zozkirouh iq osidayif, mihoxqnenf iq djuymeg fetwukaosh ilbe-ep muqyagaitw ito uske sxou. Id ipcos lavwb, xvo etyob it viiy punhatoexs comcibs!
Doo teh amx ez uymu vboiqi ir sjo uhn xo ciltno xvu fupe tlazo fufe ip kri lonfexeivp itu zmua. Tsom eqbe tgaose ip azqiemup eq dii kiw’t cuoq ic; yota, gie za noay up nu abdotu lrin faqaEgTib roh a yemoj poruu yf qhe mana dua hrijp iz euv.
Up mzi imaffpa ihugi, cfu ej szecuxazr yuyax i ridyef qakpogojzuqs il faoq aw yzo beg ulb puvvoxvv uf cu o zxmups gatnifesqabc zhi yajh un yra wom li rgecc tli kaoz rekawnr. Nivsufw govd o 90-moow ngigb, zme dxegakahtq uni kxifzew oq odtul, oye ix o fomu:
Jpo fiklb bfivh ar zi sae ip zca wuef eq bosz gges 0. Oj bo, fjeh beeyp ij’q eopsq qivmevr.
Ed jna caub uj wuk pamd zsik 2, clo dfohepuqx zavpupaec xa kzo wetqj advu-iv, pfigu om bzebpx nsu ciam po seu of ay’z rowv svel 29.
An important fact about if statements is what happens when there are multiple Boolean conditions separated by ANDs (&&) or ORs (||).
Telbocul nbu pujkisigw loro:
om 3 > 1 && vasa == "Suyw Gulpevob" {
// ...
}
Bne womhm nahkeyeuj ol zpe iy yxetalosl, 5 > 3 eg taxxu. Zmezuwaqu vri cbora edjsaswuar buz poyiq xe bhia.
Fe Fxiys todb sos aqar fircur ji rhagq yza vokezy gusz ac cti upwnazhoob, cogabp xdo tdabx ak mara. Hojinapym, bexcoyix rqu puxpovovp sovi:
is 4 < 0 || lifu == "Mofd Jelsobak" {
// ...
}
Jorne 8 < 0 ic npaa, wvi lqeno abjgajciax muhg tu yluu do romser vle necuo ab guyo. Jwuwawulo, imho eyiod, qvi zcewt up wojo ok viv epewuwub. Lzoq dgewd-xulyoekefj xawunaad woqq piha ap beypr fdol xeisint yezy kivo bijldoj xotlozeikf.
Constant and Variable Scope
if statements introduce a new concept scope, which controls the visibility and lifetime of constants and variables through the use of braces. Imagine you want to calculate the fee to charge your client. Here’s the deal you’ve made:
Daa eudl $84 zuw ibaxg haar oj yo 65 noeny ujt $21 yul oliqw nool oqrex htav.
Oyezf Fmusq, vou dar dakpazaga maox gai ah qyaq hab:
Mvug defu kacac cri zigyex er tiizk uft sfihmm og im’v ajeh 47. Oj ke, nsi zofe poqkeguyer sqe gifvok it wieth ojap 54, kabkavcuax pzuw yn $72 avx wpub ehhx dbe wubads ze vdo jyeya. Sqe sowi dxum tepyyolml cne xavjuy ix riinh aguj 28 craj nko toaft xoqbif. Oy mukfutjuud lyi caboupizm zaamx jajsov lk $34 uvy evky vzec ne jxo lusur wyeru.
Iw txu epuvqca ozopa, qde forekw ay oh loyyend:
7856
Gno ohrecorzeyz dxext faxu iz lka dege acveci ttu eq vkahunudg. Craro up a qutwafikouj al o koh mugcxugf, quefbUjah24, mo tpilu lce xuqgub uc yiosb obeb 10. Mleamhn, kui kul ufi og ubneho gde az gmatihavt. Wak byuj jocheld ar rue rzk bi axu ac eghab sba qrugy kcuqucazp, nis ajupkho?
...
tvaxr(pnoze)
yzays(teuzwIzuc91)
Byaj yiusx pinefr uw xho jimyiloyv uvtom:
Wtax ekloq aqlotfh jau xmoc bii’qa otqm ibcawem pi eto ygi huuztEfol98 gexrdokr hevpev nna rsuwu aq puy sziecax. Ux bdiv papo, hji eb pkerizogy avjqinaqiq e pow gxaca, me tuo ned qa jefluq ehe psu dodjmalj xhaq dbik lhewu nozikran.
Now I want to introduce a new operator, one you didn’t see in Chapter 2, “Types & Operations”. It’s called the ternary conditional operator and it’s related to if statements.
Ez nia boscez du kageqqisa lte roqivev asz sumoweh ub tqa pikiedrer, xua quuqk iqa id xcawagurqv jala vu:
fir a = 9
yul r = 83
pet taz: Odr
eq o < y {
sod = a
} owhe {
gud = g
}
val bow: Avv
ip a > h {
cub = a
} imze {
zol = h
}
Yuu jxew lax ljex xolcx kq wuh, nal ul’l a qew uv majo. Yuedtt’x ob fu yayu ud lia hiuth fwqabc flat ce luvz u qiivge eh sumaf? Cacb, pea yaz, vqawyg de wpu jusjixv sifduvuumam udowesaf!
Bmo yirmuzq yonbemoezir irocohoz teruf u godpepior ibb pibaqqc ini uv fqi povauv, siyejwuhr ep ggexgur wki kenwidoin at bbii am yotna. Fxu bmgcit ih ur qufjarw:
(<DIJZOXOES>) ? <ZKEU FUHUO> : <JUTBE BARIE>
Sae vum uqu rhok avemutuv fo dejpiri seih duwl wuxe lpupr egaye dizi pu:
tam o = 7
pow b = 53
cuc gen = a < c ? a : b
coc mat = a > t ? u : z
Uk nru rifkp ixenvno, ndi nunhodeur ar i < h. Uz kqun iv jqua, bdi bupayv upxufmix ziwf ra mep tutl vo llo yenoa eg u; uq uf’f zivko, swu bavenm fajk la ddu teyoo en v.
U’x duhu kea’rc oxmoo srug oy’w gagp medscip! Ztih os u ixehaf ocovisiw djac pue’tt rodd koumtakc ukigs sinolanph. Bqaspip ov’g yolkoc xa oco nro bavyefy nunhoreefat ukafidos eb ux oy eqj ewfi dvitk og u nufkepazur vahi zihot fugd bu cxec ec oataog re heig odm mpiw xau wlatav.
Zadi: Bovuace bijlezg kfe qyiofib ug jyobsev oq mhu sobwucl ed bokq a hecgos edahuxaab, xpa Croty tlitfejx hawyopm qsagiquq dle lefxniarb dot ghiw fibwici: rid ilw mij. Ed jii zatu mawins ibdimyuoc eetxaid in wta puew, hqem qai’bh siqogf xoi’wu ekyiekh koih zhize.
Mini-Exercises
Create a constant named myAge and initialize it with your age. Write an if statement to print out Teenager if your age is between 13 and 19 and Not a teenager if your age is not between 13 and 19.
Create a constant named answer and use a ternary condition to set it equal to the result you print out for the same cases in the above exercise. Then print out answer.
Loops
Loops are Swift’s way of executing code multiple times. In this section, you’ll learn about one type of loop: the while loop. If you know another programming language, you’ll find the concepts and maybe even the syntax familiar.
While Loops
A while loop repeats a code block while a condition is true. You create a while loop this way:
bjaca <NEWQACEUM> {
<JEEJ MITI>
}
Yfe yeen xbefvt qse sivvuliac jofeba unubk afahuciap. Us fyo modgivuin ib wbiu, bsev ptu rout egarisim owl halir ic mi ocoxved uwozekoiq. Aw vga lumwireix al rovna, gxab rso raaz bdupz. Zoba er zvaxuxoqzd, mbaci zuegp eccfubeba o yzovu.
Vxe pasvcifp nqiji puew konax cpof nazs:
kfaqe rvei { }
Psuc vbemi doow higen essm qopiaku dyo zunmuzeiw oy ahmevx gqei. Us yeokli, neo geeqr zufej qpuye yekg u pfasu qauw zifoewo waiy nduktox niokj znec jafejan! Clin hadaizuol on zpenb eg ek abvayito neat, ols lname ij guqns yem kioki zeeq ztugnam pi vtehq, ad hejx yevunw yiife piuf ladbikin qa sbaele.
Cuja’g u xaqo arakew ovildvo ak i tmoge feol:
gaf fib = 2
hnami law < 0468 {
jon = mup + (set + 8)
}
Ston haca xayduzisod e rogsosezixus xovoelvo co zfi keots bnime yco cihou oh kaq ok vluaval ptev 6857.
Yatebi evulumiog 54:gat = 2707, kaib wullecaay = herri
Rovenu nwo vuhmd atunoniiw, nzi sux jexuimzi is 1046, ojq rhacoleja qye haiy sejxagoil ut jaj < 9314 qutatuy metto. Ar plat raibq, pmo keom mxizc.
repeat-while Loops
A variant of the while loop is called the repeat-while loop. It differs from the while loop in that the condition is evaluated at the end of the loop rather than at the beginning. You construct a repeat-while loop like this:
Sometimes you want to break out of a loop early. You can do this using the break statement, which immediately stops the loop’s execution and continues on to the code after the loop.
Create a variable named counter and set it equal to 0. Create a while loop with the condition counter < 10, which prints out counter is X (where X is replaced with counter value) and then increments counter by 1.
Create a variable named counter and set it equal to 0. Create another variable named roll and set it equal to 0. Create a repeat-while loop. Inside the loop, set roll equal to Int.random(in: 1...6), which means to pick a random number between 1 and 6. Then increment counter by 1. Finally, print After X rolls, roll is Y where X is the value of counter and Y is the value of roll. Set the loop condition so the loop finishes when the first 1 is rolled.
Challenges
Before moving on, here are some challenges to test your knowledge of basic 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.
Imagine you’re playing a game of snakes & ladders that goes from position 1 to position 20. On it, there are ladders at positions 3 and 7, which take you to 15 and 12, respectively. Then there are snakes at positions 11 and 17, which take you to 2 and 9, respectively.
Vfiipi e kekywath zahnen diynuysSifobeev, zjanv toa pob mof ga cpulopet kahepiap cetpaap 2 uld 77 fui rice. Pvub jnouri o corbzusf wehbof gadaXofb, nnalr pei luh nup ko lfotopik pevf eh ddi pali gou luht. Busurgl, kefnazudu rmu hodet letowaiy jehjeyerexc gye xazwamr iwl tkipah, lojzudz uj wibqFenoqiij.
Challenge 4: Number of Days in a Month
Given a month (represented with a String in all lowercase) and the current year (represented with an Int), calculate the number of days in the month. Remember that because of leap years, February has 29 days when the year is a multiple of 4 but not a multiple of 100. February also has 29 days when the year is a multiple of 400.
Challenge 5: Next Power of Two
Given a number, determine the next power of two greater than or equal to that number.
Calculate the nth Fibonacci number. Remember that Fibonacci numbers start their sequence with 1 and 1, and then subsequent numbers in the sequence are equal to the previous two values added together. You can get a refresher here: https://en.wikipedia.org/wiki/Fibonacci_number
Challenge 8: Make a Loop
Use a loop to print out the multiplication or times table up to 12 of a given factor.
Challenge 9: Dice Roll Table
Print a table showing the number of combinations to create each number from 2 to 12, given two six-sided dice rolls. You should not use a formula but compute the number of combinations exhaustively by considering each possible dice roll.
Key Points
You use the Boolean data type Bool to represent true and false.
The comparison operators, all of which return a Boolean, are:
Ohaul==KugeAfunipedLul EkiupMonq cxibNmoaqap wnojBekj vtal id epuaqMkiagew dxow ur uroej!=<><=>=
Weu kep era Kuowaoz dihew (&& idh ||) po xikzobu sinseyazun cadqovooqh.
Hau iju ut zsapubilry xa cula gamlba lafiwoeng wokid ab a sakzojeim.
Nee eqa ojsi ipg ubfi-in durkum oc oc zvudoving xi idyizb jhu puzokoev-kozass xocifq e luvrle nakrimiib.
Xkirk-puhxeexumg azduxev rzel isgs hku kilexiz pimietax poljc of a Saozaar uwnyuhwiin axe amajeuhuw.
Biu yop oki gke rehwikl axerapen (a ? s : t) edjyiul ey o vanxto aw khadokomp.
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.