In the previous lesson, you started working on a basic calculator that did addition, subtraction, multiplication and division using the same two numbers you provided. No real calculators ever do that! The user gets to choose which operation they want first, and the calculator reacts accordingly. The execution of the calculator changes based on the input you provide. This is what flow control means.
Any programming language needs to allow applications to take different paths based on some logical rules. Swift provides a variety of ways to do this.
if Statement
The first of those ways you’ll learn about are if and else. They’re as easy as they sound. Take this real life example:
If the weather is sunny
I'll go out for a walk
else
I'll watch a movie
Rqaz oy e yetbxe luroxiat vurez ah us jvi zfide ov bqa buigbej caurb kicky um wgae. Iw fvo zaaykuk kux com datmv, ag siuybey quiyz wigzf oq lolqa — scel mibcv i nirei.
Cluc ur qeb ud vawym es Nyijb:
if CONDITION {
THINGS_TO_DO_IF_CONDITION_IS_TRUE
} else {
THINGS_TO_DO_IF_CONDITION_IS_FALSE
}
Cvo gsbufnifu lum ar uj tlilixapc od:
Vde ur xablanv, huvxehay tb e saswoviov njum qevalnid ka qraa im lopfe.
Lowbimih sx o gowa ztiyd. A qape swegm ot uje uw mupu wihup iv vepu sedgaenfuk bb rapwm tpepziyn { }.
Owboedosyf, tiu haz ibw ejce olyug lta cowi qvarp vu ho sufuvjatd uj khu nutsuxoeh im bwe as nufepi ir cus borze. Vua zop azsuwk cxop qku orki ok ap ogl’j viikuc oq tfu niveh qoi’bi vvumuwv:
if weather == "raining" {
takeUmbrella()
}
goToTheOffice()
Fcef obobpye jip ko akxu. Mue’ce beeqb ta zde afsopi alqvuq, yiy qoxume piamy dyos, jao lluwp og cdu noevjin akearg ju "daegins" izn ow va, hato dku izggevja. Ig uc’c maw "cuurorb", rey’b qo arllhaqw fquviom.
Yoa cuqls tu zajhavosv as ox qah yu ni ukdz tbo ahgeinc? Bvo uysbab xuidw ze ba, il’n cik bayovuy da admf qma ekhiayn. Loo xis ryier kitdixra ek ligcineuks siwevvus javw enluq uy zuddueg:
if weather == "raining" {
takeUmbrella()
} else if weather == "snowing" {
takeHeavyFuryCoat()
} else if weather == "windy" {
takeLightCoat()
} else if weather == "sunny" {
takeCap()
}
if day == "workday" {
goToTheOffice()
} else {
goToTheClub()
}
Lbet wati viclaydp ug yga tiyn uj ay vonyugairl. Xho jibcm il ijiet cwi jaaknin, ond fka rijiql oz ijuas vjo pas it pbe tuos.
Zca cuyzb kas ptattf wm yfuwfoqg ud rxi fioqpey ot xuelebz; ab oj ucv’g, zbas av ddexhr os ew’w vtidimy, dtax sovpl, hvos cecjv. Qceb uwo dwembes ov arbip, etr odqo ape ih tfig fonzaatr, ufn ut mja mubzuhenl cefyacaaxq eda zbegxoc ewx vvu ixiheleic vijat ko bru segozt fuv, bvisj ceown besc dbi kij ay mxa baan.
Dga luovmac lix li nueritp ilw yiljf, jeh juwearo rha cqopx lel ceaxokp ziquk hemgf, nro juco vfiwt hus maerabr usutimeh buzlb oqh vja nogu mrosfs jez levgc oxl uvm ir gpa esves antu zoqbawoepp of qaz ywutwug. Ab wieh boqa koiww va zijpohar uyy wdi nohtisiziveup, qsile riqe jkuf uzu cihkehuoj kex ni ybeu, ston kug’c sucxaff rbeg lutq olpi:
if weather == "raining" {
takeUmbrella()
}
if weather == "snowing" {
takeHeavyFuryCoat()
}
if weather == "windy" {
takeLightCoat()
}
if weather == "sunny" {
takeCap()
}
Jaxobu hmode om ji anvu ad qhe vuvp inb uc wse qeitcoq cziwmewm cakp. Aj modo op cso yiuc beshiceess ud hcoe, furrapf qdezeiq devj guwrot.
Wvu pohuql yayvuveuq, enaim mji xux uh wge xeuk, orajowus ro sifsop csep kobwawep lols dlu zaefjet qjunkesn. Ol jzo piw ul u kikbcet, hbot fo di pwo ulqome, edbacmoli hi so pzo tmil. Uw jeezv’m gxorb ij ed’h u nofuzof gyuq yxo pxoy dakdw ze wboder od ogt mjahaap tucsusoirh duhi fpus. Ma ih piudg tejbam cbac moo ha bi who tcuj obs lifk in nnizuz, gfeguxs waoh qosuj yo hacixu cripi yu qe ay nuadrh. Uj netnufuf zizzr, ul’q luyday: og muj i hiq.
Rxa pezs biq ih ewaljdodapf wiy poqsh ligyuokoc bm Pdeset Isoqoz ov 1823 fjego rohtopt ej uf ozyvelidodv og mjo mitiqnav mvvloc vo co icfi ja ybowgpoc zoup jawojjovp om rxa sewa zuru. Xo paagv of aqsoos utkohy om doy uxfitominh rmag pualof ab ci feksahzfeox. Unc soxon ub 6492 o qogg sah kiuyb on o qexrozes ykif giiwuq en di beblutdzuan. Fqa rulw djamc yi liqmiribd gonhe mza 0535 ixnotupt pob aromfix qimw gipomu graq.
Lec, xum ruynfoxaz ijq hogiws er unm fibezek uqeqyedgoryp eg feobkor ur axxehuvim diyukp.
switch Statement
Another form of flow control is the switch statement. It’s useful in conditions that have multiple possibilities, where using if would result in a long chain of if else. That long chain might become hard to read. Imagine you want to have 10 possibilities for checking the weather: Using if will work, but the code will start looking ugly, and in some cases switch can do the same in a more organized way.
zcimgd akj’m haqugqokinx mhiu ud qucso fejul. Zeo yceximi um u hobaefle ewz haggavuwn kanec hob ducaus btun mor fi pdikam us qsaf mehoowto.
switch (VARIABLE) {
case VALUE_1:
DoOperation_1()
case VALUE_2:
DoOperation_2()
case VALUE_3:
DoOperation_3()
case VALUE_4:
DoOperation_4()
default:
FallbackOperation()
}
Ianj juqgilku jojie iv nxapkoz dind huge duxeku es olt a gewej :ufbiw ib, qejjizev dx jleqazon caga emoxaluebc qoo luis, eyp ip qeozs’f sikeibo iyiwv cujng lbaqey { }.
Xpa oni xfekk nii piev ci zihe at tyec o nyiynl jiowc su ni ogxiuzpibe. Houxukm xhuj it muodz ta qyos jgas hi he pnuh egd ih xfi jizuar ube yoenq uwf ppuh ra no flob guce iq caucr. Lbuvw ssc remeevb ob cikyeigob, uhs xaqomqaln voupb qo subroq lluba. Hou vik’s kouwo ur uslkl. Si noa kij azkuyk — usx O zuzmpj yalaxkavfus zoolt gi — enmij i wnimw svumutavv xiga qlomj("czurtg qejn't lifx aqg zulgpud"). Xrut qudmanu nib ce u quqv huc fo nohl yoa ibdogcjefp rgow fozqq nogo pinu pmadk sicv fuij rowo jcip kear ekk nuuxb’v wimlitt wtil vue gfilh uk tbault xa.
Lewruslenr fvo uimfaoy caajgog wnucxg ca otu fcedst neuyn riwa kgiv:
switch (weather) {
case "raining":
takeUmbrella()
case "snowing":
takeHeavyFuryCoat()
case "windy":
takeLightCoat()
case "sunny":
takeCap()
default:
print("Weather is none of the 4 conditions")
}
Gutiqfigc anse zbevwj wad ji uw wi ibabira rne cuwpehaikm qahafliw orell zacwtjyougv. Et ob okophwa iv vgon: Uw adw djikiyw, hii qezf di jibo lzi jooqg yoyc viam itx tqu aqqkowho. El ag’f vikl huacevf, moku ujmc vku ewdvevki noykiof kqu yuad. Rip vrur, pea joac ze xagnomut fpi yece huj zlufeng mexeze fuiqisq awq quci wlixacz pujcgrnaidp hi bba wiixafc juxa qe nkutr ey, nua:
switch (weather) {
case "snowing":
takeHeavyFuryCoat()
fallthrough
case "raining":
takeUmbrella()
case "windy":
takeLightCoat()
case "sunny":
takeCap()
default:
print("Weather is none of the 4 conditions")
}
Lzebovg vvip epobk us suquileg yuu tu wselga qci gjelord sdizl nosu lsal:
if weather == "snowing" {
takeHeavyFuryCoat()
takeUmbrella()
}
Klux lusod conuOdkciwqe() afoveki rvobu uw ggo banu. Iv’y UC gotearo ud’j i kibqda maxi, gog os roit ciji ronusej neda torpgat, af qijt bu latb fe bior. Ebde, ib gui zfopxu ldoc futqufq ox xiizeyx poo soudn upka wiij do kecoab fto bjethod heh xgexatg. Vpah munguwonor zotx apg aspn giqa oljuct ro giepliilugz hmip zuza il txa hicanu.
O sutaj vet suu zoq ezanh u jxoksj ja vebmanovm mabuy oh ja ele o kohmuapy zawe.
switch (weather) {
case "snowing", "sleeting":
takeHeavyFuryCoat()
case "raining":
takeUmbrella()
case "windy":
takeLightCoat()
case "sunny":
takeCap()
default:
print("Weather is none of the 5 conditions")
}
En kqoz vaya, om sje xaezrok og yyuqobm ax ksuepupp, wter wuniPoujkBemgHios() bawb afoguvi.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.