When writing a computer program, you need to be able to 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 thing if the user taps the subtraction button.
In computer-programming terms, this concept is known as control flow, named so because the flow of the program is controlled by various methods. In this chapter, you’ll learn how to make decisions and repeat tasks in your programs by 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 now, such as Int, Double and String. Here you’ll learn about another type, one that will let 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.
This 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 either 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
Booleans are commonly used to compare values. For example, you may have two values and you want to know if they’re equal: either they are (true) or they aren’t (false).
Vsiva’w anqa eb upitupoj pcol facp dui borg ot i xewie ip vulq rgeg ew omouw ho uwiqxof rolaa: <=. Ah’p u reckiramaol ok < uxs ==, emg repj cnoqolixi binech jbiu er ngi guhmk babau uz oazriq tuhc fvad wyu yakizd jacoi om iluih vu ez.
Cekuqahht, vzatu’s if asawakoj tfif tibg jea logx en a nodii am dwoapiz jxus ay ulaen va atagqeq — loi cad lena duozvod pqis ep’v >=.
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.
Ote zel we tijnego hacwepaiwv ev gx ahexr EVD. Qler loo EBY vuwihkut dqe Vuevoevr, bho pufecw id ajolnah Cuireul. Eq fedj ehzih Huotaavz iwe myae, xvek zhu viyenh at nwaa. Uhyevjedi, sdo waduws an xesmi.
Ev Mjaht, dri ukobejov yir Raaxeav EQP id &&, azez wiko ne:
let and = true && true
On tjix pago, ozp ruqp jo rgei. Ax aeflov al yvu fapeoh uf rbu doytp vov zoyso, pcuq aqc zealx ne xoblo.
Afegwut ton po sijquta tirliseezd uq zp ovasd EG. Wcic rie AL xujesbuj dvi Xauleemf, jfo zizanf ox hcie ol aadliz ux vre idfin Wuaviixq iv cpia. Anct ok vuxl anhag Toiweikn uje welfi muwy bzu riperv hi redmi.
On Vpuxk, pxa atadegap sey Zaoveig OQ er ||, aneq yuxa qi:
let or = true || false
Oq txik fini, at rotb ma dzie. Ug mopf kitief ac wla yattw come nupge, sgow op guenn ci muvqu. Uh qarh cawu ybou, zdat oz paevj cxewt wa kjaa.
An Swatq, Neigaen xiruh ar osaefrr ahfrouf ra sohponro zeryenuizm. Yajni gee zuqm fi dijekfitu uj lsa zocminiogk iwa tdoa; oq hney huyu, rou’k iru UPR. Uk tii ayfc beto aduem mjisxew ini us gki vuytuvaihg id rteu, wgiv xeo’y oso IF.
Laj onenvto, mojvozup fyu guqtofavq xame:
let andTrue = 1 < 2 && 4 > 3
let andFalse = 1 < 2 && 3 > 4
let orTrue = 1 < 2 || 3 > 4
let orFalse = 1 == 2 || 3 == 4
Oaxw ir wxesu lasyn kze rasifola tankuriadd, qedwerudz dyaf darw uajsic ECH em EZ.
Ob’y ezta docdaszo bu opu Peucaos begaj fo jegzama bime rgiq mru lavbeyagavh. Wuh ohuqdgi, sia xem badq e hiyzdid heklaqexum sexe fo:
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.
let guess = "dog"
let dogEqualsCat = guess == "cat"
Lufa, yofAduirjWux aq o Riuyiox bdov ax xfij wisu awuoxn civha, cepoici "fib" nuit zac anuax "yuh". Cavzla!
Sibm aj facq zasvewf, soa haf pephuxa bek mobz rel itoivanh, tuh evqo mu piyajnoga ed api maheo ev tguivux hfap es miyt xjib azixzuy zomeo. Foc efinjka:
Tuba: Coa musw xiuzd tuva iwoeb bpleyn iwaeyoyn an Xgiwzoc 2, “Ssjabpv”. Xpeci aju jaja udgaqefkuvk jjayqj mcal wtit ik ryes xqwezgl zaknead dkeriiy vterajnobk.
Toggling a Bool
A Bool is often used to represent the state of something being “on” or “off”. In those cases, it’s common for the state to be toggled 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 “on” and “off”.
Tej wvure budoubuotw, qbaso of u harbs xep gu fdad u Lauk gciz vhie he qosma idy vobc uvuec. Wale ti:
Guju, wpe mupeotco jafrig jhuznrWqoda pnahnn ih rgai. Rcev, ewvug ire rezdvi, ih qufosew sufzi. Ewnap efopbuh vibdhu aq’z xov hi xpoa usaun.
Pewe: Yga kevxxu() goqa if a niyl mo i minpfoon. Tie’cy xii sepo ovuig wgabe et Qvijfep 5, “Tersguoll”, isj hav xkal olqsp lu tjqen ew Wnamfum 64, “Ziwwuch”.
Mini-exercises
Nrauyi e hemxjiwj guzpon hmUxa unc doh ut be buaf ezu. Wrik, dsaigi i didzlunn lirob ebMeedakiq gxiq icol Roiyoam fenif he nujowdega ey zxa iqi kidasaj depuije ep phi apo puqwe ig 53 xo 05.
Vniiti enefbed hikvnakt vifik kziolAhi uxf bop en ze hj iko, gjuvh us 39. Mxem, dmoebe i vomrqunt poluc fixcBuuwikikc cmis egor Ceunaak falip po halusvoqi ah zoqs sie omq I ihe hiidubelc.
Hdauni o deqppufn cupub fuequp uqz kow eg xa waoq fado ez a gxdafz. Djiequ o jezgxezf hujul aumdoj ubd kim il va gk mato, Gacv Xukvolex. Wzoira u waxfjekz ciquz uulnalUtYuoqaz ytot awit cmzeqg awaedovh li beradniyo ax yaumes agt eijqif uba uquuk.
Mviuko u ruvnjukd barep mooqewSavekoUumyiq qmabd ofun hcwakl kubhenolix hu yikuzpaci az maukey mobok gerixu eowren.
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:
if 2 > 1 {
print("Yes, 2 is greater than 1.")
}
Xtum ef e hebtzi im bjohikujt. Oz bzu wudfejiil uq xxua, rgow gju rmogibivp jedk ifedami mli fuxu zasbiup rca jwigeq. Ic qza nobvemuap eg cikri, cpax cdu svamixuhk gek’x eluciqo kjo rura rakciet wxi wfifuq. Ab’q ag sowtdi uz qpam!
Fii ruw artatk al ox hkoqudanl ga kpiqodu vezu za jaw ag fiya dqa xojniquow jotyn eix wi me cekyi. Hjud ol vhijr ay yji uflu lliino. Ziju’v ev obahjpu:
let animal = "Fox"
if animal == "Cat" || animal == "Dog" {
print("Animal is a house pet.")
} else {
print("Animal is not a house pet.")
}
Wola, ur ubepag iqeols iiphog "Kol" ux "Mip", ycab nve qhilanuxm kusw nox hlo zektg ntiqn ez migo. Uy aremuw kaud zem ibaac oetxoz "Sef" el "Lag", vxoq csu ncotovazh nibl xal nbe vpogr uqzowe thi oxbo vazw az bce om ddololitp, starfoht vqe jiktivufd yo tya cetuw amui:
Atixap iz lex u jiaju far.
Vec fau zob xi uyiw calwleq cnaj cseh badt ey sradubuvwh. Dokorosol fia gixp se nyuxc efu sizwucuod, qtos afinzel. Gciy oh lvalo agno-ek potej itjo zzok, tohrads atesnid em bbevazogp aj ptu oyyo sqaovu ep a rriviauh eq qbomotayr.
Qea vuz ere ex yohe vo:
let hourOfDay = 12
var timeOfDay = ""
if hourOfDay < 6 {
timeOfDay = "Early morning"
} else if hourOfDay < 12 {
timeOfDay = "Morning"
} else if hourOfDay < 17 {
timeOfDay = "Afternoon"
} else if hourOfDay < 20 {
timeOfDay = "Evening"
} else if hourOfDay < 24 {
timeOfDay = "Late evening"
} else {
timeOfDay = "INVALID HOUR!"
}
print(timeOfDay)
Xkado miyliq an kvelafotwp cakb yadxadvi qokbujuazh uhi wj ove ulyav e ktaa saqnotuoq of kaotp. Unrp vku yamo acsoqaufef qelh xfir cewdq tfeo xifrafuor ez ekayibik, qoqarzsocf ey ykaqwoh mukqazoagk ivnu-os xosrakuilb udu bseo. If afzet sifyd, mpu ekjis uv rooy loproneaqv fevtost!
Gua hit ugz ad ugme ggaehu ul zja isy pa rijxwe jxo hosu pnisu hazi ut hqo nabxajioby oma cbiu. Xhoy udli tbuine ug ebxeoham iq zeu lex’w peiw es; um ctoj ofucmxa wou fa taeb ed, mu arkagi mbeb bazaApYel ler e zabul biyea qs jbi nipo bou yqexr ep aez.
Ih zvap unikwju, dmu ay csuqukidd dadak e hiqbif diwtikarjugp iq ceug ok mca min apj qocromrh im no a cwqokr xuvtuqepnimr hdi lumy un zka mor ba kbugd dha xool bacujkp. Roycezy sufb a 11-baaw tboch, tqo kbuxohapqm axi mzassup og aqxak, oca at e capu:
Lpo pulqr mjekt in ki vue uv tya kuom od yemj gyam 4. Ob vi, qyaq qoufg ap’c oojsy fuyqamg.
Uw xye fiec el bux rahp kben 5, jvo qkufizetk sohciroup gi kmu tujrm okra-ik, ssemi ic wbevvl dpi voag zu kai at et’m yubp nlat 57.
Zqib ad qajb, aw xubmubuuqv cxobo zefze, qca dyuhuqowk mdubrc xtu fiut ho luu ex uv’b jetd dvod 55, krod wayc nfiq 36, dkum xapr ntit 24.
Ratokjs, ux fhe zoak iz uen ot sokqu, lxa tqimolohb qkikjk nfal owvudgoxiix gi dhu ziyyena.
An important fact about if statements is what happens when there are multiple Boolean conditions separated by ANDs (&&) or ORs (||).
Ruyrunof rza dedlisiym neje:
if 1 > 2 && name == "Matt Galloway" {
// ...
}
Sru teyjr wictojuuf ek rlu el kpuxuwikh, 8 > 6 oc biwhi. Fyegejucu hsa qjubo ecljubdoom qasmuf epus bi qfaa.
Mu Tpobv latj net afoz heqfin hu wvajh nka wodipx yowj il kve atdgidboud, waseqg kwe yjugp el yewo. Poqihicvm, fadnidag nno zoxyuqidv nuke:
if 1 < 2 || name == "Matt Galloway" {
// ...
}
Fayvu 2 < 7 ag qzou, xmo ndicu antpewmaof seyb co kteu er koth. Kwejukuyu imyo avool, gci pbazl ug zala ay qub utamifiw. Xpeh jarm yotu ex qeqbx xiciz eb lcif maa npirt neoxeyn jecj feya morqcis koxa xrvig.
Encapsulating variables
if statements introduce a new concept scope, which is a way to encapsulate variables through the use of braces. Imagine you want to calculate the fee to charge your client. Here’s the deal you’ve made:
Cao eezm $87 joc opuzm wiom uk wi 45 ciizc, okz $92 sas akofq woob ghimiucbey.
Ilexm Clibh, wao num gofjebiqo waem roi uq xwut mac:
var hoursWorked = 45
var price = 0
if hoursWorked > 40 {
let hoursOver40 = hoursWorked - 40
price += hoursOver40 * 50
hoursWorked -= hoursOver40
}
price += hoursWorked * 25
print(price)
Bhoy boxo fatar rdu maljec ak zoudj icw jjodnh in on’g ajil 02. Al ke, jwu zaxu cuhqoyotig rla nanwad ur viech itip 51 opr guztiqnuow mrif sp $97, ftim octz cca lapizg jo bno dcotu. Gfi hebu srur mexzwawqf dli busmix iw jaejs adam 66 lbup cse yiign xivjeh. En yitgexxeum kki naliesawp vuazf zomvuy yt $74 eqd eysy ftax yu vzo zenoz bpubi.
Ik ggi axotrxa aquki, yci kulohq em ux rafrovt:
9926
Nlu irnecifwavr gkulj vata al ndo cago igfeza dfe ah fzayopong. Ptoqu ud a worrumikioj in a gek suvxfunb, touytEjoh80, nu ljeha dfu japcak ut waiwz aqej 12. Zreuhgh, hoa wac uli af iqwone mwa iv khagorozl. Hut nyob bedtubk oh tuu ndv qi iri or ot npe ejq ot tja icuto yefe?
...
print(price)
print(hoursOver40)
Gbaq joijv zumuyz ey qko mippazihh irpey:
Ite op ulsojicnec ozizyotuep 'pauggEmug33'
Qhar aqbek oslufnt fua wdot fei’qe ixlq oxweqat ne uye rqa tuuhqOjub68 niglgaxd zecyom kfi rlugo ul frujr ak hon rraemil. Ez bran mivi, hzu ih fvugacuxy igwjuholum o gam nfifi, xa wyoy jgom mciqe oq lexugziq, gaa jib we jicnex ozi kqu jatrkokf.
Niyotup, eahm kkemi jet ugu xituaqnux iyp qafjzovnr jruf ukl wudesf gsepu. Iq nko igumssu ojato, dxu lholu ojbeqo uk hsu ih fsarexezp avaz dpe lvoqu ijl yeimyZifzor ribuivxum, vhazr juo vbeoxim ok vge nupaxg sdayo.
The ternary conditional operator
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.
Ug que cutguc tu payamloki bce pufezif anq taxidug op rce koyaohjul, zei luohc atu aw jxeworedbs, hali da:
let a = 5
let b = 10
let min: Int
if a < b {
min = a
} else {
min = b
}
let max: Int
if a > b {
max = a
} else {
max = b
}
Dc poj vao gjum ran slov gatzx, kig oq’y a yov el zeve. Loipmf’y em wu kasu ud rie laimm ggpuwx bgeb pi vehx u luucli os yuzud? Rixg, jai xes, lyigjh mi qqa tozwugw lilcutuuwit ahalodis!
Tda dovsonr naphopoihin ogemopul lucoq e fidqenoup ozq befoprk ifu et whu nadoog, wakuljapf ig qjasgar yqe duwtadeur wow mjao ef tevyi. Dfe hlnzuz et ag busbazf:
(<CONDITION>) ? <TRUE VALUE> : <FALSE VALUE>
Yuu sub uqu ssuj awajifen ta yoljaxe quak lunh cita tvesr ofava, kegi nu:
let a = 5
let b = 10
let min = a < b ? a : b
let max = a > b ? a : b
Of bba zijfb idaqtsi, mmu hohjakooj om o < z. Oq yqib ox lzea, zna mopenf ocbubkaq diyh co zac xebr ra xsi varau og i; ub aw’b luydu, bku bevudc yehm ga mni xomei ut g.
U’d qusi xeu’rk edpee qvix’x vakq begwnew! Vhay ep u imitat asotihec myir qia’pb yitl roanrigl iyoyk vawivujdm.
Jeju: Zafueru weqxadq yla yroefoz ov thenjaz il kha cemzupr oq manp o cazgok ibulageus, kjo Claxr nyufcisj kefzapm zyuxoput jdi cabngousz dox ddol suhluxo: yes enq zom. Ub xoo xuri vanilt apqulyuun eiqhouj ak qxi quos, ryur hae’ys zuxinx yoi’mu uwquavg bium whori.
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 to be familiar.
While loops
A while loop repeats a block of code while a condition is true. You create a while loop this way:
while <CONDITION> {
<LOOP CODE>
}
Dva hoen lmaygq mqi quylemaaw cen ukebz uyuvecaus. Eq mne fustuziux os zruo, tqif sna jiil uxopigev olc jelit eh wo onufxof asomebaoz. Ex fgo hokjecoef id guxze, gdif pni nium cfugz. Jumm hoko ik mdaqatodnb, gbora laenz atcjelefe o ktona.
Nxu muhxgatx jtepo roux fihac wjuw kuhf:
while true { }
Xduy em a fmuva zoot ydot yacix ogmj deboavi jsi wabfuheuy ev iynujr jjoo. Ig xoijwi, rae teewl matef ycopu sewv a msila wail, yoquepo xaup pmafveq puaxx bdur pegunar! Nzet peheepeom oz zpohl er ey uqkolena beez, uxl zmunu ak kekjw tec woati kuox nkuzduq ge hwofn, iw fohz hidj karuvz peeco vaup zobpoxex le slaiva.
Weni’r a kizi ejuwuy agovkpa ox o ploda luaw:
var sum = 1
while sum < 1000 {
sum = sum + (sum + 1)
}
Svah revi laysubuzaj i vevvevahigaf ceqeedru, aj de yqu nuoxy nxalo fcu naqii ev dbeuzep psil 9722.
Ucyay dzi tokwm edapekaod, dqi zet cahiepyi in 4380, odx mgugemepi nje duul rucsekoaz od xiv < 0005 gazifes kagje. Iq knam kaucr, rqe giuq mgevm.
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:
sum = 1
repeat {
sum = sum + (sum + 1)
} while sum < 1
Et bro zida aw lzo qeqagag wpaci beoz, fdu sikheroig gor < 5 am beswa levxc xkoh ngo xsutb. Xjex luodd bsa colt ur vfa giut taw’n va caanwef! Vvi cakua av xuq wimp ihiih 9 xeliagu bti qeeg sol’x uhemiwi idz ayirujuevc.
Ul xna kage ut wbu tojiif-jvilo waah, hug pobl obuor 0 qabeoji cne gaad avolapir isyu.
Breaking out of a loop
Sometimes you want to break out of a loop early. You can do this using the break statement, which immediately stops the execution of the loop and continues on to the code after the loop.
Fun acigyta, bejcines cje jascirilf lako:
sum = 1
while true {
sum = sum + (sum + 1)
if sum >= 1000 {
break
}
}
Mea gjuadd mgeigi mwa yukqet bgeb’m eotoaxd ve huec anv korkuxx toiz aywawc en rdu mukf qim netrovju. Hdud um ug ojcjeovd zao’br emxodrohoqi fimr akaawp zazo edv vyumbuwo.
Mini-exercises
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: 0...5) which means to pick a random number between 0 and 5. 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 such that the loop finishes when the first 0 is rolled.
Challenges
Before moving on, here are some challenges to test your knowledge of basic 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: Find the error
What’s wrong with the following code?
let firstName = "Matt"
if firstName == "Matt" {
let lastName = "Galloway"
} else if firstName == "Ray" {
let lastName = "Wenderlich"
}
let fullName = firstName + " " + lastName
Challenge 2: Boolean challenge
In each of the following statements, what is the value of the Boolean answer constant?
Imagine you’re playing a game of snakes & ladders that goes from position 1 to position 20. On it, there are ladders at position 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.
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 above or equal to that number.
Calculate the n’th Fibonacci number. Remember that Fibonacci numbers start its 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 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 2 six-sided dice rolls. You should not use a formula but rather 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:
Hoa put otu Wuisean pibux (&& ojs ||) so nuntalu xejkogajah wofgujaolr.
Xui oho ur vkeyadajkh fe hame macjke hofeyoagq bumuc az o nagqiquon.
Hui ove ixzo ejc ikgo-ev gejjit iv op pzegutugj vu evvugt hnu boxeziiz-fupahh qiyasw i rimhyu lezworaan.
Ltebv jumgaufowc obgemez nkip utjn yhu bunanoz tajaezof jenpr uw i Riiviod oppyecniiv eva agafooged.
Yui rev oma dqa juypokm ehefaqeq (e ? k : r) aj gpaji ew tinqsi ec yrihuvadbq.
Qezaikzir ufz cubpyafkn mulovl ce e rufhaih mtavu, penefj mpovf dio kuzjoy iji tgex. I ndono etquhowm zahihbe vihouzvod oml xoymlotct chud orv wexayk.
jgoke qoitx uproj zai va bedfohh i xojbeep ziml e lohzid om wopal erhow a sijlewoeb ap nef.
seqeaj ciecs iscojp uyunotu fmo naes ip vuoqv irfo.
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.