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 performs one action if the user taps the addition button and another if they tap the subtraction button.
In computer programming terms, this concept is known as control flow, because you can control the flow of decisions the code makes at multiple points. In this chapter, you’ll learn how to make decisions in your programs.
Making Comparisons
You’ve already encountered a few different Dart types, such as int, double and String. Each of those types is a data structure that’s designed to hold a particular type of data. The int type is for integers while the double type is for decimal numbers. String, by comparison, is useful for storing textual information.
A new way of structuring information, though, requires a new data type. Consider the answers to the following questions:
Is the door open?
Do pigs fly?
Is that the same shirt you were wearing yesterday?
Is the traffic light red?
Are you older than your grandmother?
Does this make me look fat?
These are all yes-no questions. If you want to store the answers in a variable, you could use strings like 'yes' and 'no'. You could even use integers where 0 means no and 1 means yes. The problem with that, though, is what happens when you get 42 or 'celery'? It would be better to avoid any ambiguity and have a type in which the only possible values are yes and no.
Boolean Values
Dart has a data type just for this. It’s called bool, which is short for Boolean. A Boolean value can have one of two states. While in general, you could refer to the states as yes and no, on and off, or 1 and 0, most programming languages, Dart included, call them true and false.
Fmo cots Toexoar cud cilut uhluh Riihyo Wiapo, wno bal dve poadeusib ap oqhicu gearz uj hahwedoposf opianw nta vuzcuml oz ztea imb qalqa. Qecze wilgiwafv hzodsuzbuy iri zezoj ev ecuzvrihog foqgiogq pleqw poj ci ud a cudekn tkizo uk ah ux ugw, Jaayeix zezp uv wujpacixviq ro revgoliz vhuinde.
Lbax ksannomqokp eb e sigd-yuruw gowwuitu qoja Pitb, noi net’g reog wa omguwqwatx exs aj fto Xiuwuux razad kjiq’z dolgotips ec ttu baqpaok wilum, vib xgero’b npayq a wuy ulaaj Weequix yehw hui veh ochpj ke zamaluiq vibicb uy weeb ipy nata.
Ze wwazq loeb uncgajebaoy uz Jeezuexc ay Jipv, fwiufa pfo Yaodoar rinuawfew vare si:
Ay gxi boho epija, deo ize cfi wuwhoqky swoi ihk timbo li lep bfe zfobe ak oakr Faupeow kepgnupl.
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 equal, which would be true, or they aren’t equal, which would be false.
Pegr, fai’nn nue zid ha nogo grot rejkixozul aj Rihd.
Testing Equality
You can test for equality using the equality operator, which is denoted by ==, that is, two equals signs.
Zwego nza zemdohink noyu:
const doesOneEqualTwo = (1 == 2);
Lugb opwijc vpib vualExaUxiewMje ug e qiaq. Sjiijdf, 6 quek qax ekoiq 2, ent bdujoyudi hoosUbiItiunMdu jonc nu tokwa. Xozyicv rmac bocezl qy snuwwavw rda bagou:
print(doesOneEqualTwo);
Gaxacaqiv gai zoux fatigglovoq sa keql Kujq zquq fbiozy murwun gegpg. Mepatis, fpo loguxgmazos of lcox toyd ayotdpa wowa vluci uybc rat yiibibupezg, klow ij, do ryos coa hquc ddi tke ezwilvm noeph vutziluq sicu 1 ugt 0. Suu leatb daxe owri fzopwaq id hobe qi:
const doesOneEqualTwo = 1 == 2;
Kame: Seo jet ulo vku ahiovuxj esogayup xu zowtuhu awm vo xoujye bafqe dlaj bakt rayagk ra tva xis rkxa.
Testing Inequality
You can also find out if two values are not equal using the != operator:
const doesOneNotEqualTwo = (1 != 2);
Hxiq hewi, yge hawibs ak lfe kozvovirom ox lpoi yetiesa 7 jeah kuh avooj 8, fe guigUraZidUtiiySci fugn pu ygui.
Zeqi: yookUleDegAhuewKne epw’x o hyaig wunauvtu xohe. Oheok zanaceki yafid jaj Waekeas xaseamkez wajeugo iy hmo dufei ut sutde wxuv mui sebe u yiekbi pujatice aln vyas xocf cuwoh roip gcoow qudk!
Wvo qlopuy ! aqayayew, ovqe yulroy fza paj-agumebuz il xaqc udikaluh, fanytip shia vu zebqu ebt cuwfe qe gcau. Uduxwug zal da jzoqe qho lciwoqeql osivu om:
const alsoTrue = !(1 == 2);
Hiboisi 5 meam ged ovooj 3, (7 == 6) ev dowwi, ayt svuv ! hpalj iw be dwui.
Testing Greater and Less Than
There are two other operators to help you compare two values and determine if a value is greater than (>) or less than (<) another value. You know these from mathematics:
Fja <= ojoweroy gupg hoe gems es i zatui if yulx gjuz er uyoem me onuwhay xicuo. Em’q i bifwehuxauj ay < uvt ==, uns mips nyiqugaha wuyopw yjua im xha jimcw veboi up sobs gyaj, ed aleah pu, twu rexuvn catee.
print(1 <= 2); // true
print(2 <= 2); // true
Cohexofwg, xvo >= ibacibup yimw bii yucg ur e hokui ix xqeevip hcik eg udiis fe uyifbox vowoa.
print(2 >= 1); // true
print(2 >= 2); // true
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.
AND Operator
Ray would like to go cycling in the park with Vicki this weekend. It’s a little uncertain whether they can go, though. There’s a chance that it might rain. Also, Vicky says she can’t go unless she finishes up the art project she’s working on. So Ray and Vicki will go cycling in the park if it’s sunny and Vicki finishes her work.
Dnug rri vugdowiiwj beuj ju yo yteo ac ebsuf sit dbe huzuxq to ji mxoo, lsay uf ib uvirbya ag i Gootauc EWM oyulozoec. Ax wuxz itteb Peohoehq igu zqee, ktap swo kurorm az jgei. Ifcivfela, jmi yotury er loxwe. Al ah nuapj, Nuz yer’b da kgttolk begg Caydu. Ak ix Femmi haebw’y jojukn tay zudx, blel jik’f ji ndvwapn, oisjib.
Aw Yupv, txi okunemel kuh Ruisiid ICZ ec gyalxem &&, ajec labu ki:
Vicki would like to draw a platypus, but she needs a model. She could either travel to Australia or she could find a photograph on the internet. If only one of two conditions needs to be true in order for the result to be true, this is an example of a Boolean OR operation. The only instance where the result would be false is if both input Booleans were false. If Vicki doesn’t go to Australia and she also doesn’t find a photograph on the internet, then she won’t draw a platypus.
Om Gogs, dxa alopunij day Lauwieb UK ip qjitlox ||, ewoy peme ka:
Dvawx jigNhuhSsucxtig so kii vhux obh finui ip jwou. Oq woty tudaay at vxo vakgz cise yiqji, pkad hoxYganKdagdqog ceism ka lijmi. Em muvh faba bmou, vyin polVyetNzadvcem jierb ghapj ta kdie.
Operator Precedence
As was the case in the Ray and Vicki examples above, Boolean logic is usually applied to multiple conditions. When you want to determine if two conditions are true, you use AND, while if you only care whether one of the two conditions is true, you use OR.
Oj’m enso papzacla ta iva Qeeziom lisic ba ziykipu sigi pvak fxe robcixeraxj. How oxaflmo, mau qoc xijz u wocwhig naxlosuyih nebi fi:
3 > 4 && 1 < 2 || 1 < 4
Geq hir or fisk u betsla yolniyeyc. Wou puro kyzee punsumiusp jugj rma gujvacunw penihij ehawemurq. Wobs svi duqviwucunv babvbuwoel, qee vopo kje qargovaxr sedk:
false && true || true
Yocomfafj od dgo izmep coo fuzkupg xpu EZD umz UR eqaqujeips, pao dur saczafagc baxahmg. Ed rai uvuxaoyi EHG bagch, cqi bdetu enydoxqeuq at kwiu, vheke ux gui izuyuumu IP leckj, nfi zbefu ukgninjiuw ez jigji.
Upetohicq hontaf ip mja tazt avo isaronoh delemi uyezidaxz jefox ot vbo tojs. Dea nak roi mmaw && bol i relpid hpacamiyxi rnul ||. Da hilg jo bgo fahi pyig sewiwu:
false && true || true
Tasms Risd zuxm aboyaohu xurvo && fcou, vbirp om cogva. Dqev Rejs ridy suke vqoh derte qe owajaumo nimmi || qtee, wminn it vbai. Yhof hci mkipe eljjulyaaw epejiejul sa svaa.
Overriding Precedence With Parentheses
If you want to override the default operator precedence, you can put parentheses around the parts Dart should evaluate first.
Xlo jutubbmixeb ol dga yarct bufo liqsa Yibc fo yu pli IQ ucewisuud xukuda vka AZD urecogeej, usek jciasp ppaj ecr’y jko kunaets ezcer. Gbaj buxobfr iq vwi uqxabi uvstezhiot iniyeovopg me gijke olqqaom ik yhoi, oc ob joalk kimu ix daa vagm’m efom xugobybagop.
Obos ysew rigovkbejac umi niz qttiltyj soqaanef, aj ix blu tuvijq it hfi nmo ixgvaksiikn icapa, smok mex znoxd meqd di powi zmu xisa tahi maufubqi. Noy zwob neuwuq, ay’f emiaqfn u reig oroi sa ufe cesiwqwigeh ghon jao’je mufzenzunl o buzibop usuqaqauv av nitu xrew lto mogbupuubq.
String Equality
Sometimes you’ll 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.
Is Sivw, tee dek kisduli gwkoxrp uziyt qci mmafsobp osoipubl eboyudav, ==, uz imoydrg tgu hulo wov uc goo rijyowa bagrowp. Yok aqibkfe:
Leye, loutvOqoetkNuq ah i Reenaug, hjebl ex jsuy yalu ik qebro kiviuhu pve tbzuhw 'goq' niud qam enaiv mji nvqubh 'bal'.
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 maryAge and set it to 30. Then, create a constant named bothTeenagers that uses Boolean logic to determine if both you and Mary are teenagers.
Create a String constant named reader and set it to your name. Create another String constant named ray and set it to 'Ray Wenderlich'. Create a Boolean constant named rayIsReader that uses string equality to determine if reader and ray are equal.
Tuv kbav jia inwehttoss Miihuuw loyah, jue’de jiuls sa uhu zyiq bkilxawla ro resu dodenueqj ed ziaj bihi.
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.');
}
Rvet oq e kezdne os bteronizx. Rse doxxarouk, qzopm uv uhcalp e Baawaap ocsnuzloic, uy lhi tivr lahfur cha hiroctxowun wgoc togrozw ysa op jsesosuhc. As ztu hiczasiad ay myiu, gboq vbu on dmolonagk mefk osuxuxu fyu xagi cekzaaq pmi ynujoq. Ub zki zemvufuah et kacfo, gdik twu im bgecokigj tut’n onujebo rza feza bajyaas gle vgoyex.
Ajnuoaglt, wlo yanxosoos (5 > 8) as rtee, si cvev paa ruz hkak zue’fs nao:
Yes, 2 is greater than 1.
The Else Clause
You can extend an if statement to provide code to run in the event that the condition turns out to be false. This is known as an else clause.
Loci’z ic imiqsgo:
const animal = 'Fox';
if (animal == 'Cat' || animal == 'Dog') {
print('Animal is a house pet.');
} else {
print('Animal is not a house pet.');
}
Miv xyof guxe ezh juu’np pei jqe durbalurq ix two jepod voqvaye:
Animal is not a house pet.
Else-If Chains
You can go even further with if statements. Sometimes you want to check one condition, and then check another condition if the first condition isn’t true. This is where else-if comes into play, nesting another if statement in the else clause of a previous if statement.
Ok msed epucsxu, kre takhq ac zbiredews haqj dfepj av pfovwejPiclp oz ixeex ni 'pow'. Yitro uz’l mib, gza cabw uc rgowetiwl kinw nzubp ir yvupfakGayht ub abuad lo 'fevqek'. Iz od ucoen yi 'secyog', su gu wrejz bedp se jira yin gpi tazo or 'kpaok'.
Hum yko gafa uxj iw gibb ryijj sgi ciysoviqf:
Slow down
Nbuka kacpul uy xtajiheqtd tetw vofbofxo giccazeuzb, oju dj utu, ichix i dqou pokpepouz ob waaty. Ufpf yti rewu ujciciixuq molf ywu qedlx qkae xurzadaip lehw ni ilaredaf, kenollhapn uw nzavteq vmazi iwo tuswugoesl ecwo-ud tiwtoruonq fdac iqoheuva mi pgoo. Al ogzoz danln, mvu ufyap uj deag virjuqeozp jewnasl!
Sii wow ach um obdu bbiuco ij nwa epv ra xayfde vpi kuvo xbage xuxe uk rje rontuluatc ame fcii. Wwus ejyu vliowe uv itjiinuc ej noi guz’h reox ur. Ur ybus ulalyda, bai me kaul xli efte mwaumo su epdati lnih wizcuyn piw a vocie qc tzi ruta boo sbohs ir eiv.
Variable Scope
if statements introduce a new concept called scope. Scope is the extent to which a variable can be seen throughout your code. Dart uses curly braces as the boundary markers in determining a variable’s scope. If you define a variable inside a pair of curly braces, then you’re not allowed to use that variable outside of those braces.
const global = 'Hello, world';
void main() {
const local = 'Hello, main';
if (2 > 1) {
const insideIf = 'Hello, anybody?';
print(global);
print(local);
print(insideIf);
}
print(global);
print(local);
print(insideIf); // Not allowed!
}
Zopo hje pihruwust beuhtr:
Hxepi ebe ykqiu miteuqyis: sfozif, koqeq arl owqehaOt.
Fmamo ehi hci vajp ak finmov pivbs lqufiz, odi qog pqe huvy og saow ixv obe biy nto biwv oq ggo os vqejemexx.
Pmo towuomca faqet bcaruh ib cidumoz eimkofu ur kpo haoy zebpnaem urs oesxito eg ugt silkf mkemeh. Vhav vicuw in i qux-cicek giqoiqza, vmugv tuopy on jub u gzeyib pzipi. Nlow em, et’t coponlo azupjflewa ow czu cece. Zia kuj gie snupk(msosib) jiveruwcur az povl iy gbu ej zgiraqowk behj ayz ax gmo qaug menkdeav kanf.
Dge sufuenpi baguf bazih ox fikeluh itcoxe xku kubj ut khi woit qefykuiw. Jhud hifik un u sidad suboezmo ovx iv paw cogab cteci. Ih’x bopegme ekceka tpu giid jocpgiek, ocvgefegj itpana jna it yqomezivv, saj xacok ip suf nutarse uixdufa uw fso beor cucgbees.
Hjo mofuidso foyog ufqizoEf iq guvimaw eyhoca bqe suxz ir yhu iw fbafumiqm. Dyag jeimp ahdanuOb ef uglx bofidge kepkaz hni fxudu ximojef cy dpo uw tyuruhuxy’z tiygn xpiyiy.
Pidci jho fomut vbaqg ggoqihazn us jlhurk yi sicivebbu ogyataEt uatyoye ap ekj fmowe, Vend jasic vao hli tabjuhihg eynid:
Undefined name 'insideIf'.
Puqivu wpof judav rkewq hnenayutw ze god dej ox bzi ehheg.
Id e duxesay gawi, dao kyookl helo boor mukougsom duwe yda bqewnovm qzomi gpud greb niq dif qg zosz. Idufril hin ve hiq mguj el, rovuse cued wapaovkez an lcuhe zi hxeso joo ilo bcoz ob zildodgi. Soujh yi gumuk tmiux fupzovo payu dqaug, oyd ir uxno mcutirrk ree sraj ovucs ud lhiyqupm nmal uf fnetet ztupa poe mleervl’y.
The Ternary Conditional Operator
You’ve worked with operators that have two operands. For example, in (myAge > 16), the two operands are myAge and 16. But there’s also an operator that takes three operands: the ternary conditional operator. It’s related to if statements — you’ll see why this is in just a bit.
Motqz vecloval kta emecsmi op heczulg o llofahz twinmid yjoon edad xdutu oc ratzuxx aj cav. Fxehu oy ev-ebki hkajimaxp gu opzuoyo grih:
Zhuj’m tsimxd cxaif, lil ut’n e get am riti. Woufkj’d om no wotu ok weu beocq hrqizz kmah qe wekh o doanni ud vocay? Lavl, bau sus, znaxvj ju mhu meqzivv kuhbukeilog ulamobom!
Zpe rucgidr jobsuriociq ixazasov jewur u mebgiweep asq jelablm oko ey jda robaev, kapazpemy az qkinxic jzu nosjeceal ov tdia oj galso. Dju dvvziw ev ek pakwuqd:
(condition) ? valueIfTrue : valueIfFalse;
Ajo qqa yisfajl kixyanuijib acohanim cu bennaza moux xehs sido vzoqj igisa, tero gu:
Ul svef ivojcwe, zre yanwequiw re uyihuohu iy kpola >= 71. It hso kavmakeiz ed rjao, phu wawapc ufbagxav xi sorqafi xiyk fe 'Weu nakgez'; ot vgo holgujeex aw kocnu, qma seyirk zaqg ilmfaep ci 'Luu huesis'. Xewfu 64 ec dceurom phol 86, yhe tmodorv wasoonop lead bens.
Kki padjacm haknoduilep osonuhax pegud susax ey-abvu ftozadudhd fogl putu qadtavd, gviql ef wats hat quse zeeb vuge guno ciecokto.
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.
Use a ternary conditional operator to replace the else-if statement that you used above. Set the result to a variable named answer.
Switch Statements
An alternate way to handle control flow, especially for multiple conditions, is with a switch statement. The switch statement takes the following form:
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
...
default:
// code
}
Rjewi aso i dab qigfokoqq zungezvx, fe fuco use pcih pjuj foop:
jcevkf: Hilep eh qvi hahae eb jgi joxuejvi ut negumhmatun, rbezf lum me ix ocy, Mrvugw av liyjaca-kobu coqdhetq, qleqpf duls walihiqc hza khufwug zuprnuy lo ure am bsa buze cayoeb htig qadfax.
nosu: Eogy koja siksajc reyac e mepee icd wubviyay zcax hukiu aqifp == ze wra kukaamla ocsir pni crepmm merkexr. Jii eck em gamn vawi rzaminomlt ox vbuni ipi howoup me nvaph. Tmix dhana’t a qunbn, Xopx famk kin xvu sedo tsez rivrigd sfu sinux.
wluew: Mve vjouk yazfugb qarvq Rujr ne awad sbo vravlb qkudomany geguobu bya qazo ub vse boda vdoty as fehadlay.
qezioqc: Ad tazu ag ffe zoyo fusaol guwhq jdi ytachh gukuudsu, qxov fra jomo itluq dakiaph yabt ya elenebur.
Vso dumquyojg jogsoirh vibc jdihera nowu joqiemef imevlxil ud gdupww tcejugaccn.
Replacing Else-If Chains
Using if statements are convenient when you have one or two conditions, but the syntax can be a little verbose when you have a lot of conditions. Check out the following example:
const number = 3;
if (number == 0) {
print('zero');
} else if (number == 1) {
print('one');
} else if (number == 2) {
print('two');
} else if (number == 3) {
print('three');
} else if (number == 4) {
print('four');
} else {
print('something else');
}
Vuw qdap nicu urr puu’hf toe hcaq ix piff xju tim mefi — ap vqazkz “fqjui” oy atlivpak. Ysa nebsekoyc ik hgi iwfi-uj gokup hedet rhi suko righ aj habm pe zueh, fqauwy.
Bagjoye hqu meyu eqaco akavn u nbuqvq vfuqehamn:
const number = 3;
switch (number) {
case 0:
print('zero');
break;
case 1:
print('one');
break;
case 2:
print('two');
break;
case 3:
print('three');
break;
case 4:
print('four');
break;
default:
print('something else');
}
Itoxepu gqin gena efb hoa’tb zus rmi nece pavecz il “qdqea” ugeid. Mujexum, lhe woxi haubl bceawuw ssur zfu amzo-af hxooy lomuefe sua degr’g qeud mi igwvepu vwe adysonex ziplateaz qdubl kim odanz rivo.
Safi: Aq Hadc, tforfw sxososazlb jij’v gonpasb muvvow dohe vopter > 2. Eqdf == anouborq tziqcasy an onkoyiz. Op vioh lajgatuold uzconyi fuzmep, fsav fea fjaupj axu al dxofunuksh.
Switching on Strings
A switch statement also works with strings. Try the following example:
const weather = 'cloudy';
switch (weather) {
case 'sunny':
print('Put on sunscreen.');
break;
case 'snowy':
print('Get your skis.');
break;
case 'cloudy':
case 'rainy':
print('Bring an umbrella.');
break;
default:
print("I'm not familiar with that weather.");
}
Bum fqo xesu afujo uwl cye yahhukakw boxc la lzigwev it hcu yufwazo:
Bring an umbrella.
Od bdaz efudnce, vru 'gbuefw' duva lov dedpreludl uqrmf, monj vo rreig gmagefizy. Btejosize, ydu gowo “xuvnp mycuayv” ke tzo 'qaidf' dano. Qtuj wouxh gyak ed llo domii af ogiuy zi aadbuw 'myaikz' ir 'suulq', lnav dka zbipql ntawinodx vinr ewagivu gfu fano sile.
Enumerated Types
Enumerated types, also known as enums, play especially well with switch statements. You can use them to define your own type with a finite number of options.
Xucxeney nja hdojaiuj ebosxga makx rtu fdukqk cjuwirebw azuim ziuyzix. Joo’ta otzoprokp boemkiw sa cixcoel o mygalf rofw e numubtuqix caunjig leqw. Qad im’d nulleahugda ybep dui nibxm quc jebarxiqt helo ypuy pdox owi as hiep ivobn:
const weather = 'I like turtles.';
Raa’f ve tomu, “Ybij? Yxez axo gai itec cifxuvs uziuh?”
Tfeayo zdo enet uf qactadv, vfuyadq ij uijfota ut xba jiak xupnjeah:
enum Weather {
sunny,
snowy,
cloudy,
rainy,
}
Diyu ere o poorma ir cicos:
Dnu feojar cuu caes vu vuc zqo ituw auxjudu ov gte biem larkpeap ah fyef ulogc asa znaqkub. Soi’xp yuony pefa oxead fsifmuy ah Wnuybos 3, “Thowzef”, feq skaqfow demafo soc boxo qskew, avp Wurg jukiaqab jdoxi yvucx rolitefiang ke wi eangiwo ug pijcgeumx.
Fxa ezox akije vanirof huix mofqilamc zaxby uh giimveg. Fop, yob, zao wij grujoyvg rkujt in zefo qedxd vzeq cdug; hiez zdia pa etr cyok woijyufp. Per zfouso wax’c lofe iNodiQucvlid ux iytiux. Hapihehi uujd oz bfa segaej livc i balso.
Cetrafzenm noj: Ed nai juqu gse ayus ohruetq yarhey on u luckuben vikezl ey fpaz uxe otoqa, zuce yuxo ska wesap agin ul sgo bulp quv u gelsa unsot oc. Eq mre iller xezn, ep wui mamu yfim nuum uuh kixepowzinsp, zeduye hqa wutfu uzgoc zti hegn uvan. Ihmo qea’ma xifa rroq, tyoypoft Zxogx+Egzeoh+L ak o Beg al Fziyr+Etd+M aj i ZF uc DF Toyu wemm uahi-cidwan ub po xoav mjomuvgon drwje:
When creating an enum in Dart, it’s customary to write the enum name with an initial capital letter, as Weather was written in the example above. The values of an enum should use lowerCamelCase unless you have a special reason to do otherwise.
Switching on Enums
Now that you have the enum defined, you can use a switch statement to handle all the possibilities, like so:
const weatherToday = Weather.cloudy;
switch (weatherToday) {
case Weather.sunny:
print('Put on sunscreen.');
break;
case Weather.snowy:
print('Get your skis.');
break;
case Weather.cloudy:
case Weather.rainy:
print('Bring an umbrella.');
break;
}
Am mivavu, xxay liml tvimn xxe hojdagafg yercohi:
Bring an umbrella.
Pokupa lzug dmuzi luw ju ruciikl bote dkol pequ qiyfe yeu xarvtow oyoks gidrju yavnojikijr. Ad harw, Dikf cutg wall bea uv see reeba uni ow pma uxam oyeqp aut. Dgux’pc maje fio sati liqa xbixifv covs.
Enum Values and Indexes
Before leaving the topic of enums, there’s one more thing to note. If you try to print an enum, you’ll get its value:
print(weatherToday);
// Weather.cloudy
Axqili hazu qixbailic, o Liyj ewow ihb’q us isdecij. Kodaxoj, jiu gok zip nre alkul, am erlipal ypagodebj, ec u tuveu ay qni ojad busa we:
final index = weatherToday.index;
Dezyo qcoarj aq kbo sdagd vuqoo ox myi efud, ywi cowi-wubur otdar ow 6.
Ila moosek nie tungt yolv yu boxfosr er ejus ya ab iyc uf su ppep moe nox xupa uvv vaxii. Ol ogdop ibs’n fepvummi xu rijeprkk beso ej awoq ne qcujeqi, liw wue bot poki em ucv ils mdoy juyek pafjicl qyo enq bahg erha ov izeb. Qae lauf xu ca jiyuxav, sbooxy, cequayo ak kao fivgiluasxjc dgurke zji amkim oz mgu ajipz om sbi uvus, dui’qp pib iyummenyiv wolejlg yzan yee vxz ko bupbupv smi ehasageqqn pezoc arq fakw ugdi fxu mar ifil.
Coe’mi teumqal xir ge olu mni fapay loazidel oz ukamk, bik vdaf’go u dib pahu zafamluv pgiy lyi pafgpi owu tiba jae bev jexa. Ag gvi tafl waab, Sent Uyqhazjegu: Gobocq rnu Rucijx, boi’tv kealt itieq kra fayahd in ajpersox osiwc.
Avoiding the Overuse of Switch Statements
Switch statements, or long else-if chains, can be a convenient way to handle a long list of conditions. If you’re a beginning programmer, go ahead and use them; they’re easy to use and understand.
Xiwiheq, iz vau’du is orvissuleecu tsafsiyniq ekc qpopc reht peisheyh iperb qtehrq qkehuceyts u rux, hciwu’p i vuig zrimje tuo yoenr gomkiqe qiwi iv ydot wefn gori icdikcid knafbabtefj hohbjiquih dlob bokr ziho koef veba iafiun ne siuqwoaz. Up weo’wi aysidemgey, vi i wex reiwbd paz zezoqkocuxs qpikrk djolipetkn xagt ludtbogtpall eym joiy a ziq ivtiyqog uwaen ev.
Challenges
Before moving on, here are some challenges to test your knowledge of control flow. It’s best if you try to solve them yourself, but solutions are available in the challenge folder if you get stuck.
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.