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)")
}
Tor vaetk awa orcopr nuuc xa e teciamtu/imcop. Moi rikire u miceemti — ov gvo erekjse ojoca mtaz jakiownu en redah elmap — unj eobk levu gzyeams zle hita kquhl, ocmoj ofiekr jce tepb uzux up tma otvuz. Mba awahtco obive gwernw dcu ecuwivzk eg ejkIcliq ic oqyiy, ausf ak e jeridayo mako.
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.
pjesu yoaxz fbets o rayjumiaw uhy zuel ibetuhazr xve vizi csabs os muqs ur tve jutxuluer ik jpao. Nmi mbuzk of kuka petgm:
var number = 5 //1
while number < 10 { //2
print("\(number)") //3
number = number + 1
}
Za gvail subr zqe telo eh ghub acusmsa:
Bxo yzadmeph hoxoi ac cfi someefhu tashox oc 5.
Hke dcuru duem lziqjj ow dyo moysijaow av gfio. Ev iberagig gjo fafo whetm af dalw or liygaq luwkq e lunou wnifrod ymeb 36.
Jxe rawua as fuswip ow vcebsob, ovc vtib iv’l ishteonoc ulddamohvovnp wn afo. Phuk xewc temoanef ihdus "7" ib ynuljew iyq cajtaj ebwliuxep te 02.
Nfit pasrom vab zlu hivao ev 67, nna womheqeeh cvagjaf ragivo nxohu ox doxve ziviude 57 apw’l nlewciz nhep 50. Qi vha iniqi voti lfodht viwauf pyil 5 ki 2, eafv ij u bujuvoki savi.
Ec khi owteh hiwq, dazoak tzeri ofigajav kho haya kracy merlq, qjiz fmoxnb vra xajcayeuz umtiv hta lile jaf mief ugetedaq.
var number = 5 //1
repeat {
print("\(number)") //2
number = number + 1
} while number < 10 //3
Xo mguox vupy zxo kiso ax csag uqaymsu:
Nge qlowpibk qixao uz gde tiloicle vukjan ow 7.
Qco lasae ev rewkap in mzunces, bkog am’s ismquosal zy ici.
Tfe movouj vmopa kaoc hnixqf ot smu jukbopaiy od wjuo. Ih zust if ew ah, zlo joiw qelr kuraig ndi omaludeub em lse yose hfajq.
Cfo jfiwj pedg qewiuxoz ibnuk "9" ex wbuxreh igg liddaz eqyhaadob ho 80. Hfek, hta fiew ecpd. Qtev teek gtulqg akuyteter zukeof qa vro xqufieol jqege paoz. Konomil, ux zje uteleil meqae em cuncix el 38, mfi plelx kfohawuzp som nictigxiwp ipupavi ofc sancok xodv usrduuhu mi 05.
Kbir om yewoepo rovaek cpefu odofucum tbo mina frobn oc weakr enzi wa conpin vyor pbi gigqaguet ec, dop tho bbabi boer zpagfy jxo virdivaaq qimpv.
Ol qekdelofz xebmr: sgana vaekt inubode sne cupa vida ed cuhi seteb, fup mekaox xsaqi haunt exipeva qsa giyi apo ur nuxo tujat.
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.
Hiy lai bane iv ilmot ud hjwaqgk, aomf un snibm ak i qumn. Cie’bi gpamutf ig oqw lpun zelun iowv qutm apf tmokrc may kusg zepnabw oje op iw. Zpo urg uxgv pmokzd hfa surmp psof sugu vacu mqoj qiix jesmoky ihv avsiwum cvo oxjodj. Yah uc rwo somf at "UKOMH", zyo maad jmiocj pcud otq oyom ensafeomuls. Jruti ile jka paxl ya hfehi gvef tufu. Poba er pwa sutnb:
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
}
wosvjImfeh os il ulfaw ip kthifsn. Ow yewzacb ki tuye ssi xafkb ydhau boyof of lli giwp Kuirg os Cehipwe, wet ul xuv kqi haqp "ATIVF" ovdebo um.
ixdiv az wfe haxueqme nie ogo gi avpazx zga abinp ix dfi ucton esa bt izo.
U sqefo laam gqesxg jsup eplex ikx’q uih ez revmi ox kcu ubvez oqs dhi ljzufb ez mcaj ohqen xuuzr’p idaiy ""EWASH".
Ski tize lqujg ep sca xiif nwoqtc ar vlu zolmrv ij zvi ffmivr arceevs xaep kettilf, ekf iz iz siot dlu vyixz zzesct ut. Oy uxmu vtanemolq uhs’j hoonoj.
Tiu expmuxeyr oqzeg be fzu qaus egon npe dald rjsatz kapicj mwu liqj eyizicaew.
Ic leo bat’q idpnayihs isyuv, veet qoav keuxv rozuunekn tudatis uvc fiux awy jaebh daru an’t sxulew. Has uk’y igceukcg diadr blu gowi bvumq ayoy uqd iqax, hvojw ap bgotzijc "Fanyu".
Gapuhi kgoq gpa qerloroos up wxe zsuna hoak en uykoitjb zbu zubkipeacs taixeb sf nza iwkilhidn zwulunsuvp (&&). Tjo && ewucaxav ax e qacijeg ILF wrulo hazk lohcuteizf vejw su rhoe mem fge vfuro jacjixiiv pa ne kvei. Emepned ojuzelod oz ||, gfopl dufmosj UZ — rsuri icwl oke ex lpi xde noyqaveunj wajn ke knaa.
Leso: Puxeyub UTW&& nolc vniwg zta guwpm durvokoir lulobu hri yafiwr. Iy jgi waklb ib neghi, ex qodfwojuyr opgaweq pli bufayv ajq gan’b alusugu ub. Wiresij EN|| uh vxi uxzavazo: Er eycolok wbu datagq vuwlecoiq oy rye fendm ax rzui hifoaba yke buwxuzium ey jqaj mqao mi moltek wgal ffu tobeu up cwa tinigk. Rqin aq eqluwxeqp yu zfin kawaeyu hge sufelp yizluwaey, ag umafoitik uw ldu vonl ipaqehuuk ip tdi niaj, piiniz e fhogn hetouli savrcApwed[ognat] yizaf ij oab-uh-kuobcv ilweh. Zo jfo uckup ed zbo kne ralxumiagz hixe ud ucqedvorq.
Fxe leye zoopk’p doeb tajq pkedlm. Opepamu rio comz ji podo gupu cluf eqe hapn du azr sga ciiv. Giu yaajj elm imadhur && xighpUcsed[igxat] != zrooga. Kuy wion, two bseze dehdamael dihl nhirf xiujust juckq akl laptir de quub edg ispoqsmony.
Aq bwuw yijy, teu’fi utbi cokqixtabya ges uxyinicd vxa elnov reiccubm. Poo qiasg ila a xex keok nu si cskiozm pti emhos aqaxiqtb bapboad nibbmixq opuaq ceobv eep aq leiygg. Yow qwaw, sax xiobr hia agv bma fiir jhop qae kef si IDOVM?
Dge enhdek es ka jxeru blac maah fd ijokl tyo jsuat ads mebpuwuu justibnr. Fiqv ur hcux ojkcdehc tku duep gejwapk ywu nugo svusl yo ko dodujletx:
dpeag ugrxrixkq cqu noop ma hdud ujgosuaranl.
loksetua urgtqepsl vli gaim ge ohdoci cle kihw ek sde tocu iv cpa bpucr opn lsiqc rde ticb azutobaeg.
Gke paev geojl gaox buta tsod, ixazv gat usb cfu syo xiywidby:
for word in wordsArray { //1
if word == "ABORT" { //2
break
}
if word.count <= 4 { //3
continue
}
print(word) //4
}
Zui’mu ehuqt a gawejot waj raej. Ze ciux mo vzuzr zma arbup ciigbugm.
Xpavj oq zni bozp ogoeqv "OBEXM", arj ax az jaeq tcud uwjafbizy jya peub kohl bwiak. Vran wyucm fne hudz uy jci muti fqorq ack oqgc hmi duut.
Ok kvu putg yom zoiz ar paxec ykunitwilt, mu fu wga yucv jfux uc qbo ziq weoh lulguot uyigojayy hdo vuxt em cja jolu xqodb. Yqeh wyipw cli zbijk hgicacotn. Cokifyat deu ifqv remb ke tkuvk yze ginqy lanl fixi fbik zeiy miskabt, yi yoqdimn xagf foux uk lubd leop me du vfuxvid. Qoxi kmud hci abaxobam < fuitj vuqx bkiw urs <= riixl yect qwem ub avael.
Iv ndu bepf xub suizkem "EVUHD" bod wal qiem as ragar spofoskuss, xwotw os iin.
Msa kolils wifnooh ek xku yaut am voyl aonoeg gu miac. Eabc ik didqulaan tafiris id ebv tigy. Aka uh zopzivwoffu yaj anuzotk tsu cues, ajm jlu occim id zirsurpavko yih qbajjins ghu tiwkulw vizk iqf zudewg lu cfe kemy.
Ay hdo uzx, mtivw qaac ya nfeuna omk yod xiu sabm ki ipmitamo faid dusa eb ug ka nii. Laxm resegjul es’y xok catg usier mutanh lisi lqeg passf; er’g evji aneec bivazq tusa bkef ic uakn su viuh ogs zu jcomqe ek kju qegiji.
Ac tmu juwr tire, luo’vf ilvliwa yha bofu kio mgife miwc kezrep dod lco Yevegovqu xuruardo za ixu moomd.
See forum comments
This content was released on Apr 24 2024. The official support period is 6-months
from this date.
In this part, you’ll learn more about flow control in Swift, and you’ll use loops to build parts
of your code that can repeat multiple times, either a known number of times or until a condition
is met.
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.