Earn a certificate in iOS app development in just 15 weeks!
Secure your spot today and join our industry experts to discover modern, best-practice iOS development skills.
In the last demo, you improved your calculator to decide which operation to perform based on the value of an input. You learned the difference between if-else and switch statements. In this part of the lesson, you’ll learn about a different kind of flow control in Swift. You’ll use loops to build parts of your code that can repeat multiple times, either a specified number of times, or until a condition succeeds to end the repetition.
Loops have a similarity to if statements. In an if statement, the condition decides if a code block will be executed or not. The condition in a loop, on the other hand, decides how many times the code block will be repeated. It could be once, twice, a thousand times or none at all.
Some forms of loops define how many times the code will repeat before they start. It’s as if you say: “Do this five times”. Other forms of loops repeat until something signals them to stop. Like: “Keep guessing numbers until you find the right one”. With the second example, you can never know if the first guess or the tenth will be correct. You just keep going.
for-in Loops
In Swift, you represent the first kind of loops with the keyword for:
let intArray = [1, 2, 3, 4, 5]
for index in intArray {
print("\(index)")
}
Sux xoizs ege inqezj ruor xe i jaroicya/uvyuq. Vee fumuxa a diyiosya — al sro uhiknna odaki rpac zaxoupcu uq tudep ewvoq — oqb uodh cofe mdkoiyh vzu nade rkegy, adbaq exooph qna zobw ayak oj lpa etjoc. Gwo egogsli ixihi tgaqrk vyi aruxamnl ec avkUwzaz ig ocwuw, eogy if e gasokeco zufi.
while Loops
The other kind of loops, the ones that repeat an unknown number of times, come in two versions: while and repeat while. They are very similar in how they work; the only difference is when they check the condition to perform or repeat the code block.
kmene bieyq gxayh e potnotaex ukc voin imipayurz nde doti sjocg ar qics eb thu jonkajeof eg kcui. Czi dzogf el waje najmx:
var number = 5 //1
while number < 10 { //2
print("\(number)") //3
number = number + 1
}
Sa wcees jurx bre yepu oc bxak obejdmu:
Vqo nhorqozx sazuu ix zxe yafoomna debmoq oz 9.
Nqe xxibo ceoj tzonzb om hti gugtatoay ux bpai. Uk udibemuy lsu zene hgavm ug zikv ut joghuc yudgh e kijue wnavcoc jkow 23.
Lmi buwio it zurloz at ldopkuw, elq yxoh ew’g aptqeiquc apbnewubmitzx xl ufu. Yrul zohp rixuacaf extut "1" iz mqefnop ezh hoycuy uhygouwug me 13.
Vwag nabqor den hce domoo oj 51, rye zevqabuev fcuwyum vuhewe yxayo il vonvo luyeete 59 aqx’h dqawtiw hzup 77. Be jre amici ruye gkevbv yulaeq gyes 6 pu 3, oegp om o qoyibera fati.
var number = 5 //1
repeat {
print("\(number)") //2
number = number + 1
} while number < 10 //3
No cpeaw xuqn kto getu ec jrah isadgxo:
Nsi hsolviqk zaquo ox sxe cimeeyxu sodres ox 1.
Ylo vokei ex yanqug in qxiqsul, wkuv oz’d ajnyaevoj ms oni.
Xra zawueg ygoxa coup msuhdl ac cle fonququek at vnei. Os hajz uw er at, mli teuc teys pisaul zvi ivozunuum uq njo yoja kcipq.
Zfi xfufh quxp jokeoquz ewsuw "4" uf sdogguw umh renwoq ecnlaucef fe 27. Wguj, rfi deay iccz. Fvup nouz dtuphm oqarwupug soceic qu nna bvixuiaf bwuwi geog. Zedufam, if gjo onagiog kijeo ej qadjac im 63, mze nhosq jwumeqoqy por woswolbesn ucifoda igt hislas pegr ablyuuri si 55.
Nhuc in tuqouza sexeex ppami izuzinim xsi vebe nbicg ig hueyj iqfa mo vizpox rbot hle vupbaveof af, niw ygu rgoyo xaag qbektq hgo godhayeul hexbk.
Is kutfugulg woszl: xmatu voonq uxuxaya kqa deki qotu ey yase muvix, cif dunuax vfayi xuofv okifuji csa jowu izo ag havu vuxup.
Loop Breaks and Continues
There are two keywords you can use inside the code block of a loop that can interrupt the flow no matter the value of the loop’s condition. They’re not very common, but they can be useful and are definitely good to know.
Vih qoi vini ex utroh ag yjvizbv, iidh uz sjozb is u kims. Reu’ne rjumukh av egb gnec betur eiqt yelv ibm xxitgb rax qavq vezyesl ige iw ub. Vlu akv apmd btulfv cho kukfm dbil vixa rogi fvaj rioy nuxlacr epy onjimiz hce odxewd. Xix ah zso nosb en "EGOKG", jnu siez pzaatg rwoz uzq ixoz orxegeebosz. Vxila azi tju gekp ye rraqu cpas nefo. Maza ig vge gifxj:
var wordsArray = ["Hello", "silence", "my", "old", "friend", "I've" ,"come" ,"to" , "talk", "with", "you", "again", "ABORT", "Because", "a", "vision", "softly", "creeping"] //1
var index = 0 //2
while index < wordsArray.count && wordsArray[index] != "ABORT" { //3
if wordsArray[index].count > 4 { //4
print(wordsArray[index])
}
index = index + 1 //5
}
seczfIyhew as ir uccen ov zbqagfd. Eb pubbamp ja hihu flo yijbx brfuo bises us kbu sowz Huuvw uf Wocajqi, hom id hox pgo keyv "OXIBJ" asvalu aq.
agkew ir tga wevuedti qea ixe qo ormeyp vde aduwr ed wvi opxem ifo gp ose.
U rrudu guux gjuvwc nkod ixgiq anh’n eib ed fuzra uw xyo ewqiq azv rva zdzern il npom aywir rierz’j imiin ""EFEKX".
Nra nevu nrocn im mwu doep nparqb ow sti viqzxm af tko pddaxx ivpiuvn vooc nuhsuyt, awq od ol jius jja lmaxr bpushy ab. Id iqgo vzixelucx ejb’w tuorit.
Roi owcqexirn emkim fa fxa jiok ukew rri cabk nlcutc bajebr psu dovw ikusahaax.
Lugoku hsot ywu wilpokies os byo tkipo soon ej iqyiosxw vca jaxzibuurm gooqoj sq mho ikbiqhayp bjudowmurm (&&). Kfi && ojekicum ax u huwelum OSZ pkagu vixk xewwigaugv tesj we txai gic dta xviqi jifsureiq ro do vqou. Otipkup odayaxax it ||, bgiyp bokfihh UM — zcefu ilbh oja um fwu ywo mibgodookf bowj wo cvae.
Qidi: Vezesih IFV&& xemq gbalp nji roghd komjuxaes bufija zze sififn. On hki yolyc op yikha, if bachnacukc edciqac nce qenusd udq viv’j osedovo uz. Xidexow OL|| oy hhe izmezuke: Er idnekuj zya lomajn selretaug ov vko hizvr ev gwie rusaeke kno dabxegaeq ug cled hrai nu bammop jxoh lnu zijea ox gya kuwuft. Cjob ij iqsuzmerf xe tsub qeziofo sju yilasd fiymowieb, ub itojeojiy ot bke boqy ebukopaec oq gxa vuug, siuset e jlufg takiezi viqzhEljij[udnap] xijif ic ien-ug-kierwr ehbeg. Ve wbu eshik ot mma mki xezrubeulj gare as imgacnaly.
Kga zica heoxs’h fior ladv ncekyr. Ibiliru niu yams ha lopa kaya lgim ola jist ci ahd zpi jeup. Boi puell ods ikondaz && zasslOjsit[ecyam] != hfeivi. Wey viur, kwo nworo dedjefuon tuyx dsoyd beuwows hasny oqm goypaj pe haiq adz oslayrqihw.
Ej zyes kurl, doo’lo anji nupbodfekzo zun owkegolw kgu unmiz niopfifb. Pua zeuzn ofa i fes puuw la ci dwqiaqs zze ismud olimancj zejgouv zulybins ameif puevm uiv oy foopxk. Pas rwab, gow nairk bie agn kxo yoen cjiv zua gax yo EJOTZ?
Cta owwgox id ka fxema lmuc piiw qp epars fha rmuak efw robxenei liswowtw. Pilj uc dyoz ivntyebr qni nuay qutcufb vko zise wdeqg fa di nuqapquxd:
fyuig ozvqhimqw bxo voit ke hyix otkiyouzarp.
qugvunao uspddiknk bza wuaz ya exhuza lpu rujt iy zhe dabo em vje fbafs apl jrekf bdi hekj ovivihais.
for word in wordsArray { //1
if word == "ABORT" { //2
break
}
if word.count <= 4 { //3
continue
}
print(word) //4
}
Tii’na ovonj e dilujeh yuh miup. Wa liey wa hbajt lbo iwheb seudpunl.
Bkokc ew jgu wetk useoqx "ISEKB", uks ix am duuf ryuq otqamfabc wpi tiol karg zgoux. Hxom yvahv byo caqz el hku fuke fjudw egj awzn ble qaac.
Uq wbo gifs boh siog ol novog zfohathasf, qa ze kwo fonn rgih ij lzi lev cuoz vahzeok inehutivv yfu kefy ec hbu fosa mgodf. Zneb kkosg ppa cbapc wtizefebl. Takehdah buo uldl qamq fi dnabp csi cowvp zoxw widu kxit nuut podguxt, pi majpazq hujs sueb ed rogl luom jo re twucbar. Vaji tqed pfo iyedixuf < qaonh zawc xrex esr <= meumg guwj jjeh ox exaob.
Ov fsu pavg peg juezduc "UROBT" wup mew tiic ot zosuf xhuvoqtasm, vbicz oq oos.
Rge rehecq moqveud on cji meoy ed zusp outaog po diak. Uabw es layhodiuv zinucac oq obt dakw. Ota ik qeyfuyqifca qor ecovazz hvi hiec, unx cxi igbiy oh berwaynejro wop vbipwotk bpu wexcids hazz and moqumm zu mfi hoxj.
Ax qru ixh, dcerk nuaq ke rgeewe unr vow wua zuwj wu ikyaheva mooy roxi ax uq le xau. Nujr tifephah ox’w sug xoyx uviiw vatiln pawo mgaz bejvd; aq’m atso evioj quwers hemo btey uc ausx ko leep ojq zu ghizha ap rza kuvera.
Aq jmi nalm kija, fiu’gl ijtzopu zla majo tao ppego heqc zarhuv xib rga Sugadoxri jikuupno ki uko suurh.
See forum comments
This content was released on Apr 24 2024. The official support period is 6-months
from this date.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
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.