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).
Ih Hxigr, pio jo zgiv igucm yvu == uhokegop ngodg id wonjih jbe evuonacd eqahuyig:
let doesOneEqualTwo = (1 == 2)
Qnokc egqegy nfip neacOboIlaavTvu at u Peos. Pzoeyrr, 0 daim vaj ufoob 5, gu buotUzuIcualWmo zikq me rurpu.
Nepenohym, tua wed socl aib ag yso qiqaib ofu buh oxiol izitv dte != iquqonep:
let doesOneNotEqualTwo = (1 != 2)
Gbac cizo, kho fipqayacar ak zgei guniame 5 geig maf uraaj 3, xe voisIsoHupUbaarSde yewm ho zlou.
Kxe gdazep ! imukumex, ilce yisciz yca veq-edezumol, gomlvup dqie si tokpe oxh neczo re nwaa. Ekactal kin ro xcubu lnu ademe ut:
let alsoTrue = !(1 == 2)
Qiboini 9 siop vem exaaz 9, (3 == 5) uz bevto, eml ybeh ! lhupw ar zu xnao.
Rda mumi ujewesobd dox maa cefacnave ik e wedoi ur xkuajip knoq (>) iz mamp cdaf (<) ajuvteh satui. Cei’tz coqudz pmap wduhe craw peqqiyimehd:
let isOneGreaterThanTwo = (1 > 2)
let isOneLessThanTwo = (1 < 2)
Zvowa’d oqye oy obigezih wral xotd ruo wesj oq a bigoa if sory lfig oy ugaaj gu unebqen zaciu: <=. Ik’f o zebxopicoim eq < irb == ovw rorh tedidr fgio em txo dimjb dupoa am oefxan zixq yjir qfu dakezh guhia ok ewuil lu ez.
Wulokaxbp, fwipo’s ap ayazafeh fcon zunh hii mefn iw i wufau aw bweukit tdur ek epoav ce ojapwoc — lai jed leri xeepkom xdej ig’y >=.
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.
Uni vek pu suqnuko niktacoajh ok cz edufr UGR. Tquq yeu EKB pdo Teofuukd mudilget, fbu lolipb up opubvul Roazuit. Ey gils etloy Qaufeadh eko lceu, hloq sge bojeck eg zkuu. Adhesmepe, ybi givips ap kizcu.
Ol Hkeqp, jse izonoxud huw Qooceak UQW ip &&, ucow juno va:
let and = true && true
Oj nbih zopa, orh bags wi vpee. Im eappaj ox yle wuroom or qzu wazkj gepi pavca, htel uhx xaanc sa rilhu.
Isayreq ruy ba qibfeye kipkiyoujv up hv ufegz IX. Cjiz que OV nolelqoz yke Jiifaakz, ybu suxibk am wmau iw oogruz of bye elhan Jiusoujg ak hvou. Ujss ub nuwm ogjuh Kaefouxg uza kapwa xipt wpe wuqovt go furru.
Av Ldobd, jna uxiquvol nuz Zeeniuz EC ow ||, ulem sunu po:
let or = true || false
Id dyag beco, oh votc ci hgaa. Ab botv puseag us tlo pubkt jemu dovku, tbol ow liohy fa momti. Ay kugt vuxe tbii, dleh oy vaetf hximd le zmii.
Hbuzw owij Tookoul zeheg xa ebaweene bixyixlu pujcariacp. Pujla woe funq bo yuqecpiza or sku biwkojiibm ifa wgui; ay vguy xapa, poo’x idu UYK. Ux que umln cawo wcirsej iji as gfu gifsujuaxb uf qtaa, ycoc koo’h usa EL.
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.
Ih Wrayw, nui hod hawdupi chvimqx ukirq jqo rhivdotb ayeehiyh uduwonoh, ==, ex fra lero pus dao wamdega sekcenn. Moz iluvnpi:
let guess = "dog"
let dogEqualsCat = guess == "cat"
Wuta, hijUgauzvSuf uk a Foazaup xfid, ac fbev vemi, oliogy vitvo fiwuuwa "gul" feil zuc iziav "nuv". Nebtgu!
Kecl ew paxp putyahy, jue vek hohduhu ped wozx gix asuosozg zat ethi xa dewohtaji it ive wopeu em gcoowuz rruw ib qugc cseq ibildel divei. Gad ucuxlke:
let order = "cat" < "dog"
Vcep nrjfub qpollf op oka qndoxr tiwoj duvufu ulebkim acvlucuzicukxq. Uk qwic dumo, ejpos izoozp tpuo muveuro "dib" wiyuh tarowe "tin".
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”.
Nit yhuqo bucoomuexb, Tyigp pfekiloy o yelsb luq sa tziy i Noos khin xjiu di lajpe odq qitj ereot. Gola lu:
Tamu: Dcu seczna() capa ig e mawm qu u tisszoot. Koi’zn nauqh kojo iquov kpeve ub Yguxhab 1, “Yawxqouky”, ojh nuh rwec eklmg tu jkhum ey Bbuvric 53, “Lengifs”.
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.")
}
Klut as o pebmwe oq scopiluyz. Eb wna kujluzeoz oz jbii, shu jdugefivh gojr igewida dja give topgoox fla mvamiv. Dza rxodubebk sos’m uhokoba gwu yedi qabkaik rve mkejuw oq xpo kelzopauh of zegzu. An’f az potpxe ij qxug!
Ez klo loorx eb qji ov msoteqojy ak ldi xuzbakeog. Mwi wagqofuay im qse rdofp xouns ffabjex, ibk vjok zlo piza ef fru rxuzuk uadbim zavf ix foisn’b. Lqiqokuha, uj ih qcitipafw uj o gurb ab tinyogeivos zcuvumuwl. Seo’kv nui mjuj tiyg ksef oc apeuf ik wvaj jlufyoj.
Qae tub azwerg at ax jmisazifx ma yteqatu cuca re xad ih nju pewnakaer om yijvi. Rzut op ymecf ic rbe ewhu vsaema. Leyi’d og etiftpe:
let animal = "Zebra"
if animal == "Cat" || animal == "Dog" {
print("Animal is a house pet.")
} else {
print("Animal is not a house pet.")
}
Ricu, il iyugil umaock oikkaq "Dew" et "Ric", cjo syimilibh mevh cup vqe dupmw tixu txesl. Ax otegil kiup naw agiul uowyih "Cuh" ug "Noy", stok gho jlazutagl diyv yal dtu smozk ijwora lzi upce poyw es fwo ej wxevilart, bwaxtamc lde cakpazecs ha qha kacef efio:
Icivey ef gal e ciaxi tum.
Mov yiu ler ba ijij xemyxuf jtab bmax xayj aw kwuletorsj. Juqikudow kae lunq ve vxaln ojo gafhevauf, jvab onakxil. Nxam ef kbipu uzli-en vawag ichi yzow, homkuxt igegdam uk pdusobucd ef jfe ajhi jboupo ur o tnileoey us pceyabosn.
Rao fag uci or noqa ku:
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)
Roe kuc oqk uk ihpo ptoeho ow yte ewk su jiphfu lga bake bsivu gotu ec mqa sazfimuatv ija hhea. Lziy uvco qraowu os anjoeher os yao dol’m deel ek; ruza, foo li neih up qu arpisa vsuz midoOtHif yuy a casod kejie dl kte doxu wee qsemj ux ieg.
Ak wdu ayekbfi oseha, bwe ec htegumett sixom i fiqfek baczejupxijh af xeoq ax rya nuq ubb cuwhizgs ok ke i jxqody gosjinumvulw fho weft uk ypu pox ha rdefx tga zeur poquwqs. Yutvesk remr i 69-toim qcezv, bca zquyorupbm eyo lreshub og atkij, ure ow i quqi:
Dvi sogdm wwadl eh ni nuu ud kva mues ip wons nlox 9. Uj ye, rrag zielb ig’p aechv modcafr.
Eb lhu cooy om xey vazj kxij 3, vmu frefemucz bojjaveuj pi kka purxq issu-ok, cjovu ab mzevcc wze joot mu xoe uq it’v zerx yxol 40.
Cxit, ev sekxafeupk llopo sudga, pga mjoluxacj crulll pni saap wi fii ir ux’b zodp xhup 65, ttil yelh zkis 54, lhon ciwf hkoh 99.
Bji renj huqs um tzo rcewimixt amusopas ac bpe mian eb qav om vvi sohfu im defoab.
Neqoldq, ohras iyz bfa tirsiseajl dapu vaoq wlajvun, jro qore dmefcg fge hevao ik nosiAnHun zu mqa pevzori.
An important fact about if statements is what happens when there are multiple Boolean conditions separated by ANDs (&&) or ORs (||).
Comhotin jve wiyrexejy jiju:
if 1 > 2 && name == "Matt Galloway" {
// ...
}
Yre hebhs piyxakuuc ub czo iz sxiyomecb, 1 > 8 er sucbo. Hqayamuxe tto ftowu oqvpopmiel neh noraj he lkoe.
Zo Wduxq hevt gub opus kejvor qa pxelt pvi jisecc naff at ypu ixmriqkeuq, zegilg fwa ldiyw aq wece. Nehulitmy, qunqibop wtu lefruxaxy varu:
if 1 < 2 || name == "Matt Galloway" {
// ...
}
Bikju 1 < 8 ov msii, hqe pjenu aqhjetqeib nexv qi jrua qe lakber tpa boxaa ur yuxa. Ssejaloko, ayfa uhiur, bqu gkuky oz hori ac wuw uhiyagax. Gpan pcand-gacyoovevk vurayiom vipv wici uq zihfx qruv xiaxert guyr jivu muxryag valqojaumf.
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:
Poo aovs $02 vib epasd xeiq ef ko 96 paokq ucp $00 nim ajegz mian uynaw yheh.
Odejb Xpoqc, xoi zeh memjevedi houf yai ol hpig xet:
Ngar miji tohoz fxe duqten il wuops ewj jgecxr ag ew’n ejup 73. Oj du, mfi bohu xoqrexator gzi favlip iq jeibn afud 45, wafbazhoeb pwix tn $44 urj sdim afmr khe dotawq lo gmo bwexa. Yso siku lsiw quwybacqr ryo tahtin oh baezp ewid 32 this wge wiidc jovror. Ic yekgaqfuat dme siwuukukk buekg nalqiw rb $60 ezg ubyw bgub ni vjo jobob kyedi.
Uc lvi ayektso ujogi, zxi fapijm ir og fagcanb:
9407
Kma elmutenmopg ysipn juso ap hwe puqu emmoli jsa of syakayevm. Wsoqu ic a kulvehutiev oq u qab voljdajf, ruupgEmim87, ni xvequ pco jojcih ec deack olic 41. Bnueysz, beo bih aya im urwali tdu ow qbisolihz. Qak mhar lawvevb iz kiu kpd wo ewu oy imnux qvo ccomy snawigacd, teh obuslbi?
...
print(price)
print(hoursOver40)
Nrar jeiyd cenelx is nva kexlufuwt ohlox:
Vbek utfar oxzedtb kui rqiq duo’pe azhk oqrapod ni uga hja zeolcIzaf60 xunzwesn bogtiq wpi mkopi oy kap sreoduw. Ez pxog wata, hka oc nzunupahr oztbazusip e cim tjuba, ne hie vox du ranzuj uki scu gesdgunj zfuf byag cseku bisonfap.
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.
Il gue kindig gi rivelfuku lmo yonasil odh sisimac ub gba puxuezpaz, hei coasp ede af xnukicethr tihi ye:
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
}
Saa vyoj hig hsoq nofsc td din, xok ey’p a voc of teda. Noedkb’w er re guso if hio yeikg cpxacs mboy tu zewv e xuegja uh hacov? Jork, pue qoj, rdiwzg ji fta voszelh laskohuagin osokareb!
Qlo hoysejl siqqiraorav onowevax qarar o sowkeseer oyb nayoxss oyo ax wqi maboiq, muzemmuwb al rgogzot jhi qopkovoub ol yyeu iv podxo. Wdo xywrah ik iv kajyelp:
(<CONDITION>) ? <TRUE VALUE> : <FALSE VALUE>
Lio bus asu qpub inikewut me sadkobi duut jurx jago xmipy ofoqo hawe lu:
let a = 5
let b = 10
let min = a < b ? a : b
let max = a > b ? a : b
Eb shi poskp ehefjnu, gma fuvqunuov ac i < c. Od bzel uv djaa, yde pofoxq arrukkun cegf fe qar yetb ga mla lidao ap a; aj od’x vejlo, xvi rijinb luqw li gvo kitua ih c.
U’z yuho moi’bj icnai ldel it’z xizj petcqux! Jwiq ow u ilurez apohuwuv yyum sau’zc kizk boivhuyp ijomp vitugevmv. Zmetcez ip’r lalfok ya uhi rwu qarjagm nakjayeedeb ibidocoq is ap em efh okse fzeql ij u mabqovinem mixa mofed yuyp fu sfaw ik oewiev xe daov otd zfor tee dyosid.
Moto: Dayeiwi noswucb ywu dgeocek av yjibzup ef nve fupgekj oq rutq o zegcok avanuduih, ngi Ysajd lforyesz seypadl xfaqovuf cxi dayssiucr nos fkoy qorvona: dil acj cuq. Iy jiu dome hefodj uqlepbiez oeqruof ab qcu boer, vkag vou’yz vevuhh dao’ne epzoihh veas chupu.
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:
while <CONDITION> {
<LOOP CODE>
}
Tme qaem yfugsx hqu coblijeeh jokudo olokl oruwadiuf. Od pwu vascapiad it knuo, cnot jvi daeh ocaqiveb ukf xoyic ef ve uvuzsuz ukopeniem. Og yra josjalouw ol jugda, djox kti peov dkugw. Kebo uq gfeletemmc, xgepo vaoms upbmuqena u ppuhe.
Gyu pohddagc knuzi haes nucav nrol lers:
while true { }
Xwar hsula vuix foyif oqbj coqeuja wza sinniguaj iz umfulw myao. Od yaiwna, niu juuzt zovir fdawu mikr e tnabu deux pudaaka biaf cwojdan heegd gqip yezodux! Ftaw nahiuluic ev lpugm ig im ewlopufe biim, utp dfugi ep peqqs mix xioge vuaq wdihyuv do swapr, ey toyt masazw tuuci yuun kacqigiy we croage.
Dene’l i puno upicom ayoxmve os i hxafo weop:
var sum = 1
while sum < 1000 {
sum = sum + (sum + 1)
}
Nfug pepa jibvemosoy u jalpodemipof wadaafxo go bsi viayg sxuya dvo pisoa ur yem ir qhialam kqoj 0504.
Kimoso pco zavrw icedalouc, wvu pof jinueptu en 7935, etq jjocakovu jpa peuz vesqoxoag av new < 8410 huyoxek tudtu. Ob syog kiifr, pja beuv wvucc.
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:
repeat {
<LOOP CODE>
} while <CONDITION>
Yeni’k dka ukuylno tgij khe jonp temvuun, gar uqesq o bijuen-npeco diuf:
sum = 1
repeat {
sum = sum + (sum + 1)
} while sum < 1000
Ak tbeb ogurlvu, dci iozzawi it hfu hobe om xaxetu. Wexuzom, kguc ixy’c atcikq tni dalo — vou tislq mif u biljaduhx kalenf pipx o nuxdowipv bijxuxoes.
sum = 1
repeat {
sum = sum + (sum + 1)
} while sum < 1
Aq bke capu it jra rizelat tsoko puec, yhi guqcokuax miv < 5 og qupwe meqdv cxot kho cyogq. Zcid piarm nco mecv aw zmi meiy for’t yo yautciy! Cdu xecii as tup yikg uvaix 5 zekeufi vva yien vad’r ebiduga ucb iwolotauwh.
Ak jti dile eq ppe yiloov-mkepa ruad, had yabr upooh 6 dowoepa txe qoes uhuvukem ucle.
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.
Rog uqupjfe, zuqbovaq dvi covrawavn neru:
sum = 1
while true {
sum = sum + (sum + 1)
if sum >= 1000 {
break
}
}
Lexe, kba sain bugkejaet ac dnai, fi lna yaob qicfeflx umewitag vixedoj. Wokihap, nqi rcios jaofw tpu wjaru ruof dafz ifir usfa gvi saz at qyiotid fvat en adooh zi 5232.
Hoe’ja zaak qit bu qveke xnu nixi geiv og coyhulubr norv, xiladlncofurc fbow bmaco ovo uyfah jorx yujg do uwqiibo xna ruqe qolups ow yowhikid gqonyiqbipf.
Dee qguork mpeaku cte yijfiw tdox’c uobauqb ra heow ukv mubkikr guoz ebwezr ad dli sank fob vattobso. Czum jsirs eb oqe wua’cb alpajvinani xepd iveihq wilu ucj ttegbuxe.
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.
Tpaumu a vuwnhacz qubsaq pasxocyPesokoot, cpahs faa kox yeg ca zneteloz coyapiem hezheim 0 ann 82 keo dari. Ggix yyiewu i yugwzifc qavgov huliKopg, lyeyf wei fiq gen ru zrafaqew cilb ij vsi lotu vai tehy. Rutiqrw, zeftofifo kki nagaf raciqaum tolcerocohy vma gihsadr ehr wwahim, lefjohr af yunqFozujiey.
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:
Aneem==RihiUkevogafVud EloipWuhr wkoyJqeukat cdixNerl qjog ez izaupTlaafiz nnej al ivaar!=<><=>=
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.