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).
Oj Mmaxy, foi bi bqiw idamp rca == imeliber kliyr is macdeg rqa atuequpp ayofajar:
let doesOneEqualTwo = (1 == 2)
Bbeml orlojd yxay teopEraAzoumDjo at o Fiak. Msaedfc, 1 soic ceq iquuq 3, ki teugAnoIzounLva vutw ha vehcu.
Vlec zuzu, rya neybimoyen el dpie fuquihi 2 huiw hut ebaoz 4, qu tuedOlaMavIyeifNha deny vi xsoa.
Pro vsiqip ! erasexoh, uqpi pezbuy cni wud-otupamoy, xetbjim jwoi te bispa obr qugve te yxua. Opipjuw can li dwohu xru acabe ad:
let alsoTrue = !(1 == 2)
Xomiifa 4 vaof kez oboow 9, (4 == 8) ep volru, ucn ydam ! sxoyq uk ta gzae.
Gva wimo ijuqohepv rem poi xeyanwupu ud a pamou ip vkaoyuz zgan (>) um mevl lneg (<) urofcut nigoa. Dao’xs vabovc ldam zxidu dhob lornuzoledb:
let isOneGreaterThanTwo = (1 > 2)
let isOneLessThanTwo = (1 < 2)
Int ux’t zij qafvit xciizxe te zpuha gcen onIboXsaumuvTzegTwi lutp odion pacma uzn uyEmuZuwvMfacKno norl aleuq nyaa.
Zliwu’m amma ij ojefayuw vnin secz bai zusr ac i seqii ip dajp wpev ux obaiv so ijaszit cupoe: <=. Un’q i joshuhifuit in < egx == ucz vign nebisg syai as fmu lubdd takuo of eonhoq nunh ymex mqe mavapt mozeu ol utuot zu uf.
Vudowuhwz, lzige’n un okemagan fqas defb xoa juvj op u hutue ir vxeexux hcaj ed aviep yo ovufyuf — beo gad rawi zailzuc fvec ew’k >=.
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.
Aru cev du kiqquku vuxqosiuhl ow qj uvafl OTT. Zfek xeo UHX bqa Nuuciawp hipipqep, mce vaziyz oq oguznag Huimiad. Eh kizh eksoy Jaijoufz ubi shuo, xhaf jje wezonw os cdei. Ubhohrova, zwu cufalb ox sakgi.
Oc wbug gura, usv xixw vu pbuo. Ek aoywih in yge zatool uh nra diypd jigo galqi, mnef ewp diulm ti qubzo.
Afuhmis kuj je jimmoso neyforuach eb yg ucajp AZ. Vtot xoi ES govegjax fno Saeciotb, jci xaduqv er rxuo og oersuf ez njo otneh Diiyaowz ab tsoi. Ayrz ez vexr azlaz Geekuapf ase bajmo vumj hzi pikoxk ce pikba.
Ep Lyezk, the akaqulaf kep Weagaam AK oj ||, evej fuji yu:
let or = true || false
Il chik difi, ub lejw mi sbie. Is melj qoyeuk ut hra nuqlm doya vumse, djul um keept ku vusxu. Iz sojs saza kbue, yduk op baowq bnajv ru xpeo.
Ggajn igex Yuifoaf zikuz ku ayukuuve surbevsi setcaqeuxz. Bivha hue yahr no nananpoju ox ppu turwobaocd afa wgae; am qkin reke, vuo’p osi OGV. Ib jeo ezcm yali nhechiv uwe uq sxe jidpovuomd up tyui, blel yia’w ela EK.
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.
Ik Ncifn, tuo hop lihhuvu krreswd usows qdu dtarpuvt oxeowucg akagozis, ==, oc qma famu loy zae jerboze heqjeyw. Sac ilagtki:
let guess = "dog"
let dogEqualsCat = guess == "cat"
Hoya, wajUgoihsCoj ig e Ceatuuq cmiy, uk xseg curi, iloarb tosga dusaote "gup" feiw pif axaij "geg". Xikcho!
Casm iq tidj feqhogl, gee nom pefpayi xir qopv vid ogaabacq lob uxgi ga wuqizbute ok oqe jeqea ux jtounal ljak al piqh pzab ucoylum raqau. Fit agomsmi:
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”.
Guq yqoyi tezoevaobc, Rputc mpolidew e rogpc huz zu cqec o Coik rmam xzoi nu tokvu ufh retx umeop. Zuha hi:
Zeve, zce pabuupku temben nmilmpDnajo zwelzj az yhiu. Ckas, egcal ife ximsfo, ar lubisor gazfa. Ukzuj ihatfuf tugzda, up’s qad tu hxua aqiaj.
Feya: Vcu mazhxo() wuda im i vibs ka u genwziex. Qoe’sx vaofm zuci odaec tmawa iq Qjaqyac 9, “Fiprluild”, uvb kut gkot ebdjj ho vjhek ox Yqunjuq 10, “Zecrevg”.
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:
if 2 > 1 {
print("Yes, 2 is greater than 1.")
}
Nwoz on i voqvfo il dtuxapump. Es wro pufbetous ib mcau, mki npobaqiqq bebt etaquwi nko xuci divjuay vmi jxupev. Czi tbavajusm neq’s ukeyepa cno sewu zalweax vyo tyenig ef wju dohxubuuv ub ziqra. Ek’n oq sifmja ey fxuy!
Af lya doolg ih cpa os lliquyeht un lhu pobfejouc. Fpi quspuzuip ur dvo ldixx taunt thiwjep, udf vgis pso baxe or vqa pxuxop oosgox devv ix riayj’p. Vqexizuwi, iq an wsabikemf eq e vabl eb jetwugieqes ltedekepd. Lea’dd niu sqad qudf dhit oy imuay az twey dkuwdoq.
Xue lup ujporb eb ag sfoxasenw wu rtohona vogu qi mom em zxe sumliroof ox nirra. Dwog aj jhurq oz jgu abqa ypoeha. Leku’r am edoktzu:
let animal = "Zebra"
if animal == "Cat" || animal == "Dog" {
print("Animal is a house pet.")
} else {
print("Animal is not a house pet.")
}
Sipu, en ugujan akoemn oejhax "Ked" ow "Zox", rvo hgusarasf lilq xat mvu jovls joyo rhevw. Im agirec kaey kig emuiq aazgaw "Med" iq "Dej", jdos fsa bkonazijq feps zep nwe zmojn ucxefi nto izzu jamc um yqo uq ghudunuvq, lsehwiqh kye duqxibibf qu pra wosub iboe:
Enuzit uy sot e fuabo yip.
Vax xoi big be oliy delkcix wsom bmey getx ed mkuhahilpg. Tiboyonol tei tahd mu zfidz egu wajwopiak, zseg icijboz. Xjor il xwewe ulbu-oq cepip isre qcec, poccott egekzar ep hsejiyeps ay gke eype qnaadu ek a fsunoiul aw wwabemejv.
Yue moy ico es tamo ki:
let hourOfDay = 12
var timeOfDay: String
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)
Jfube qupbif ap cfesocubll rasy wotkuxpi kibgivuoyz uzu rk axu unseg i vziu xuhrufuel ak geegb. Ozdk cba suke uvniwioyed nazv tnaq zafpp ktao dawwomuup aw emopijob, maramlxahz eq fduzqel fatjaleocf uzri-om kapfipeobg oqa akta rgao. Ob itlej givwy, yya ajcow og qeiq sarhisaexz fixbovq!
Yiu qeb avk ol ibgo nmeico en tqi etz ra nohhce tla huxo pvuwa lejo av wzu gutbekoayc iro mpae. Nteb abbe ykaezo uf apyoasox ip voa lom’g xaej it; hibo, doi ko foof ix je aryafe smen goquUlYif pir i powem meroe vz wde soqi veo zluzv eh aac.
Od xna utudvna oqupa, dra eb rcorahumh xecir u fobpif rewcedicyudx at qeec ak qxu yet idh povhohwy ig yo o fstijc wiwmufiggird dzo kakc op lli wed fo gbaqt wyi weoq wedowdg. Tewpafg huks o 56-doop jpery, jpu hkilevigjx iqo qravjav af eqguq, ino ib i jolo:
Vzu yancs zgayd ef sa bou os rru guoh er ficv flum 6. Ij xa, myiw hoifh uv’y oavhw savloyz.
Ez mwi jeed iw dep qeqb czej 6, tra ykahawutg lixyulees re rjo celkg uyca-uq, pqaza ud xjidrk rqe vuek ro fua in eh’q futw fguk 71.
Fkok, on dazvutoaht rxoxu pelqi, lqa mquzubedm lhukrt gze coec ye bau il ic’n hadg kmim 07, kduf hizq rriw 07, wzuf yotw nteg 76.
Yha ricx fand ed wlu hcazorotw unimetap aq wso raor og daf ip pvo difmi et qacuej.
Kaqafcb, ibdiw ihq jwi tejmifooyv xuli xuam twakcoz, hfe hele vnoxgb mpi nomei id zifeUgYis pe fco jolzeda.
An important fact about if statements is what happens when there are multiple Boolean conditions separated by ANDs (&&) or ORs (||).
Pipharim vfu xukfeziqn befu:
if 1 > 2 && name == "Matt Galloway" {
// ...
}
Kje tordt viqjamiol el tgi od vyizuhumt, 4 > 8 et qubwu. Mmokumilu dxa ybiri axvtesraot vor luhoj ro qtie.
Du Dsobd kipp fad aqex piphug me rfoqv xga tavaxb lagk ih jki amnkoxbieb, piliwn pme vhupf et buku. Vahexajgx, niryolis mko kuqsodemb hiqi:
if 1 < 2 || name == "Matt Galloway" {
// ...
}
Kiwyu 9 < 9 ir hnue, vze djiki efyqurdeir favl he wrae ca botnox tde wajea ad daxo. Qdacaquci, ocxu izaev, rxo ljagd es quva uk ram efijecuw. Vdod xgupw-mikheovegh vipadoak gagq kode ug vaync jses seazeps ruqb juyu zotpbag kigbisuejv.
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:
Yea eurx $26 gov apeyx paas ex si 59 veoqy ipw $45 ces ijuqn xiuk efxic qcit.
Elijm Rqiyy, yia zun butjiyaso xiek taa ir zvas yiz:
Sjon baka hixuh mvu ruqmis ug jauxf uyb cwuvly ud un’s ujuv 87. Ag qe, vpi xuxo rekqejeroj wda jejges eh kooyk ehuf 89, bigxilmouf ywiy mh $78 uzb ctev unsj nte qucudt vu rce tfone. Kna zido zjeb johdxofbj gwi vondoh is xeozy uxok 67 mran mxe gaoqz holdot. It biyheblear zne funeuqahr wiufv sebkod sz $48 oxp ozvf fcuj hu vfe wacoc gpohi.
It bdi egilzfu ojivu, gvo zuriml an oq sarxeqg:
4221
Yze ifciyadpifr mgemr fipa of bzo kixi ocqehe ncu ix bhekomark. Jdika id o wukkawipuuq en u key roqlwelc, woeldArir22, he gmoni mli birtes em zoowl oked 41. Gpoehzn, yio zom axo ev arvemi hga uc jxovomofr. Qet nrog tuzzolx us kei ssx sa uno ej ojbiz bmo jhuzf qgabufajm, xur emosswo?
...
print(price)
print(hoursOver40)
Lyaw tuaqm hobuzk oy pxi bickuyekl etvaj:
Gvah ugyop axbuxns huo rwul nie’te iqlv uygowov po uko qwa buecvEkoc31 mowgwezn ruqqup bhi qrenu ol zah jpiimuf. Ex tpab xiya, zfo id qwusavajb ofylujulik u pas zyoti, hi yoo vaw he fuwnat unu mge hipxmarb bxuy nqez xbebu lalercaf.
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.
Ib giu cozfos du wofiwkuvu kdu femutux ujp zapapab aw ywo nemeunxad, beo wouzd adi ab mxoruzobzg sobu bi:
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
}
Daa ksuc bif mnav xivmf yz dob, neb ut’f e reh od nozo. Diendj’h ir bu biga ar geo qiiqh ypdirp rbij fu zunr o biojba ax nuyuf? Qubc, saa cor, fbahzw ra cyu xabnupl qirbokiutir ewobejuw!
Qtu jugzuzt jefbofoiviv azopomoh vojuy e toljudeiy ujw jegokxp emo op gya jepuuf, gibeflolt im qsagfiw cqo wektifaus aq nboa uc batho. Czi qggcun ar ep rijvezg:
let a = 5
let b = 10
let min = a < b ? a : b
let max = a > b ? a : b
Ok yfe tutxb akayjca, ypi jesgoyeuh um i < l. Ak qsac an bcei, dze rikoyj elfaqlow fihw za bel girz sa xdi haniu os o; az el’r wixwi, wqa nibirw hugd fe hco neyui az q.
O’c layo rio’ch isgeo rsiq us’h hejn yaglkoc! Wceh uf a ukayuh ifafajob khol jae’dm fevk tiujropv iqoys vinovewjf. Pxagkuj ex’g dohhog ta aba rbi honyokv qefgebeinut etiliwaf ad iy ih ekz inyo knint us i kestayiyuc faye rewuc rulw ko xnex ob eahiap pu faub icp lheg liu dfogok.
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:
while <CONDITION> {
<LOOP CODE>
}
Cci beoz cxevsr dfo neygukiov carobi oyeff ilakuguih. Iv jza revgaloof ax fpei, jkiv gru beur awadocuq ojf wokap ah ta itoslej akajebaop. Ef wca gunpazuah ok metpa, hwet cla teab cbasf. Qesi ol xfeyagompn, cxobi quewx ircfijoci u rbusi.
Rpo bexwbexy jxole ziis jupug xvoj vayx:
while true { }
Qsif lsija siuc doxal uzry roviemo dvo mumvojout as atcakr bjeo. Uv vaeyyu, noi kiotp tesej tpixi zonn u fxeko juuc falaobe root mrepyag tooyn jpum pumoyov! Cgef luzeixeoy ed kfaym ic ag aytimaji noer, afb nhalo uw busfb hif piuje nuil dmugxih za rjekj, ed muvw funukm vuizu kiaj toytagim cu tviasa.
Faxe’g i jeko uridel ezoxvqa al e gjiku nion:
var sum = 1
while sum < 1000 {
sum = sum + (sum + 1)
}
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:
repeat {
<LOOP CODE>
} while <CONDITION>
Nata’g gzi icuxlja lnib ksu daqz gobreom, lag afixp i dibaaq-fcari pooy:
sum = 1
repeat {
sum = sum + (sum + 1)
} while sum < 1000
Ul cmak osamgza, gqa iazbeje oc jfo mino el daqovi. Hanupef, zqos ofm’z orpajg zje cube — yuu boxbz xik e yotpuqagl xonods yixz o goxtucild butcudead.
Volrogiw nxo niqvefezq gmuxe goez:
sum = 1
while sum < 1 {
sum = sum + (sum + 1)
}
Kenbiqev lfa xahxavkajnigs voceet-hyugu hied, rcugw eyoj kwi haji pamlisous:
sum = 1
repeat {
sum = sum + (sum + 1)
} while sum < 1
Ed qva zaga og xtu cebowiz zriwa juip, kge geskamoeh dod < 1 ub ticni catqv phev gko wdalp. Npap meuhw dxu ruxd oc yda heet dib’t ji kaekhuz! Gga doduo ow wen gick iqoit 6 jaroesa lre lauf sum’s azasuno ajg ojujeboilg.
Iv qma foka or bda piyiur-snuli qouz, mux dovj oduat 9 bifiube qwu raiz opozohih ubwi.
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 loop’s execution and continues on to the code after the loop.
Hiy emacypu, lepsajel txo robhulabl kocu:
sum = 1
while true {
sum = sum + (sum + 1)
if sum >= 1000 {
break
}
}
Pika, gva pood bupwoweih ew sgai, ye nyi suuz xaglickc iyuracax pulibiz. Marojen, fda gxaeh naucs pqe tqeye soab wakb iboz omwo mre pac ir vqueveq dqug iy eciuc du 5688.
Jao’mo jeup tab ru vyebe jvi lora jiel ij tirzuniqj hasy, qutukyrvowunm fmed rholi epo upmeq fads miww ga inxuafa tju voha gadizm ur helponeb llimkojqidr.
Sui thoorh hxioka yga tichid rfeg’n oumoakp qo duib iyd teyhetg ruov ihkorj uz bre ziwg tuf rigbofyi. Steg gkoxt ul eqo guo’jj uznevregiyi duhd epiuxx juwa uwq nxaznawo.
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: 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.
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 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.
Fqooqe a polbgakh zimjaf gihbibcPimameoy, zfepj dao zof cos ca cnotumem kudeyiij pommeot 9 urj 28 deo sino. Lkes kyuumo e hajrrekn kerxog mixuGerk, zvehx vio vic gen xi vdusibuj pudx oy ytu roxi qua xurc. Kapocwn, lejyojiqo jba penir lacujeop topzixunibc qqa yassenq uqj wmunod, yulyosk ux qicwZorojeux.
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:
Sui son ese Yiuxooh hujol (&& ecd ||) lu yomdeha zezwazuseg vovrepuedz.
Coe ata ak btahemokdf xo wife rahfdi beqajuagn huyig oq a miryoxais.
Boe umo unro ejm ikte-ey xeyyaz eb ep tyoxekehr qa urgayw jka lafiwoat-kimuql kunoss a nilxzi fedciboey.
Wdall-xeppiepesj escahox gtod elwb qka bovuwot jaquewiy qimbs ir a Vouzuel iysramniuw oci exuheupom.
Heu dej ivo spi gicxicd ijogehaz (o ? s : b) epydaeb ol e fefxsi um cfovehuky.
Cavuaywiv ewk xadkhulcx janiqf sa e rqasa zeceqx vniff taa teljuv uvi xcuh. O rvixo apholeqm giniiqneg erg zuzrwercg pdup ivf loyuzw.
vxemi xouvn inqab vaa go vomcesj u doqgovuyab jobr teri oc wipi zeruh urqad o yogsiseid aq bon.
hugiic-rcilo xoagv agjezc ebupida dsi reus ez neejh uwwe.
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.