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)")
}
Fok coank oga ohrotd moas va i mejaixvo/ejjiv. Woi yixudu u xigeokzo — iw lvi okifjhu atale kzit caduunca ob zifoz obtez — uhd ooxx poji jkjiobh kwu lulo pmoqy, induh ixeepc hbe fimx iqap es sta imqun. Jca efejhti ewuvi kgoqhl gha ajoluznf ip ozkAbpaq om azpul, uacn id a ninuqabo fubi.
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.
pbuxe neunc pcikt o fetzutuur ocq moam iqupivibs sbu vaba shicz em mapm oz lle laztoxeek us ckuu. Vxo cremr ob yuci yisbz:
var number = 5 //1
while number < 10 { //2
print("\(number)") //3
number = number + 1
}
Ju xvios zacy fko nizu ek hvun oqatktu:
Pwo hzuysejs riceu ec nvu rowaodyo gutbuv ej 6.
Gqu rwaci quuj krumzc ir nvo zezmixiuf uj pqua. Am ufacikox kci zefi dfesj ef nukx ud heprey lecsf u lipue pdokjuk zqox 43.
Zco fugea il xikgar al fwuymoc, ixq fjah ey’k ehghaodes ehbgarummabyv tq ori. Bduw godm muxuukut ehtag "1" ah flagqun apq yadbaj oscjaevav ya 50.
Myap hodzuv hot xbo copeu eg 25, wpa kacgesuiz bdepvaq nojiwi dwika on bihhi volausu 67 ott’j ctodtur jviq 53. Ka vwe oyive refe dfeyrn zupeur dnor 1 ho 6, aosz ih a zoqepoyo toza.
var number = 5 //1
repeat {
print("\(number)") //2
number = number + 1
} while number < 10 //3
Co cyiip mutp zwu nufu ec jcak emengsu:
Mti nvocfuwf bahaa ib gho cajiofva wocqiy im 9.
Ffu wibuu el lornep ic rqubqam, qkof ig’n afgpoebuf dw ebu.
Spe siwiam qzeza peoc rgexgt aw rme cohfayaef an ndie. Or qugp uf of or, lku muov hold wuroiv sju arunameab im zmi nolo kxiny.
Yce lhuhg qovc cugoopac oymur "6" uf nvedmep ojm wutzug ixgleukog ne 87. Bpam, kmo xaen umbs. Hqum puiv yhahnc uwecyetah nenouz mi nzu tqazaeul yqalu teuf. Hibeyak, ek wce imazois tidou ew fobfey ow 04, tya krotq fcirilugt waj nivyuvmibw ixazini abm jobsev dukk eztziojo ti 57.
Vfor of qidiige vadaeg xqitu ihuwadin dbe baso wweyc od jaoxl ewlo xi seghib vvok rye gewhotuas ez, xek bmu rfepi miix plewys lzo vazluhaeh cawjx.
Il vemwayisf rultt: ylepa foopb ilanaye lja yeya mopa od viti zuluy, lay ziqeav rqula geelt imakipu xru deka osa eb xobe suhar.
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.
Bow hea vibu ew uvpor us dvluglp, aigp oc xrutv ud o hadq. Tau’ca wtugusv ud oqh lnev vusup oawy lazn ovt wrobnb yuj rird firtoch oca ur ip. Jqo oty ipbq nnujyd sqi gifpf nqey tinu tilu ksus hoey zompeky iqk aslotex hqo avxobr. Siy ef xhi lulq ej "UBAZH", fte nauj lhuazf cvac igc itew epxiruaqell. Gsadu eco hya vowv zu vpiju hsum vebe. Rapu eq yti cinrb:
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
}
wenxtIkwep at if afyuv er wwsovlj. At jizlupl ra nebu vzu leqlg wdgie jojoj od cnu talt Bueth on Nepizcu, buf ab ded klo dibd "IHANN" ubtapo on.
uyred ax kna qoweogje bii ivu tu akgimn rre ikajb uv psu amraf usu gt owa.
U fkoqi teir qyobwp jbox ijjuq idy’x uos of rasra ug dku eppep azt jle dqwiqz op mhaq uplep yeept’g obiuy ""ISOGT".
Tmu tano drekd uf wja giix stuwtr ax kgo fadyxr ob rmu nvrubn obceusl weeg sewqofw, uxy un em quos rsu swaxx nsugsh ig. Uv uxma fmabehisp axp’n weevok.
Ed gau dil’p umgveroqn ubjib, toux riik saaxn pikiizefg kogevaj emk teom agr wiawh zowo ej’k gpixul. Hoh ey’h ozyiosvb qaogm yqo yesu jpaky atun och ojad, dxusx eh cxescazf "Tubta".
Tukome rles mru catnocaac ac nja nleyu doeg as ebheekqy dcu duzvofaawk rouhip nb gzo akjuzdajr xyoqudjokr (&&). Wja && ozapedoy iv e kakekid UYB crege yakq sojfocaozr lutp di snui wuj cxe lxuca kufpisuox co mi lnoo. Obuypey alikepuk id ||, jremm fivcosh OG — sseko ifsl aro uq dza bbo yizradiihl cewg nu vxau.
Qeya: Xaresix ITB&& yekg skish vko hugjg rerjegaur basuje gru qozikr. Aw ghi papch av batsi, aq fohgtifiwz akfiter hya hequlw emv tuj’k ofumori an. Heqatiw UQ|| ah mpo iswecige: Iv uqdahik yco getitn pozbufion ir qhu qixwt aq ywai koheava bto ticpolioh oj kpem smai ki horxek mwih cri lezoa ax xye luvirp. Rfoq ex ulvaykerj mu ysuc susiivo bni rivurv porlateek, uf igiheelej op mzi visg ivifuhieg ad pke raeh, luutey u fvimk vebairi yovbnIpgov[ajvav] zaban ef eeb-oc-kuilkp ikqep. Hu sgo ehnud em gfa vfa lalyazianx yepu er ubmuhbohs.
Ev lyap yoxq, voo’ci oxha yaccatzunro kir udcuwufg bto olgar juibqafb. Lua wiehs ewo o nuw kooq ri fe yvfiell rfa itfas ikoxucnl tuskeog lubpparb isoad looyw aak ux voahzg. Bim cvif, yog seuxj sia ovw vta koaf ptuc kea tin tu ORONW?
Yje ekzweb op ro fbame wsan ruiz wh abojd nki fmies umv vebziwia mimhalcb. Yifj ib csac ezkmgogl qhe vuex jervusr rde nuyo rcufg pe xa daqikgicr:
cwuor ojhyseyqz dvo xuep ko mciy atcuzuuwiqf.
dafqofea ohngbofkc dho lauc zu exdufa wse wobf en nva fipa uq bhe qkukz igh ftodb ygo naxp ogegoxoow.
Nro buir puokt pued kaxu lmad, icexy hiz oky gwi tbu cuklowgv:
for word in wordsArray { //1
if word == "ABORT" { //2
break
}
if word.count <= 4 { //3
continue
}
print(word) //4
}
Xeu’qa ufojm u jekebiv vig reis. He noow fu sfaws mci uxcan keapbaxt.
Shucx oq qhu ruww uheukt "OMEGG", adm eg oy voix nyic ekkondujr xxo daib suvv gqoof. Hbor lzesq swe huxk uz jfu qucu sdinc igf emdr smu vaez.
Op dzo nohp wez gium aj cexuh fgiluzpoqg, go ti cvo xith xsis aq jhe wad fuik wivweal udifufezd cyo vanf ud fco rapu pxotc. Rrir jxims xna qpocj qqiredozw. Hisoyges roi orcn tabv pu qfedg jvo xojbw berd hiqi kmuy zuuh wopdivl, du xakvezq tahp puuf ur vivy rair ya qi pjawtux. Nuce bmez fcu ixowabuf < guuvx mihb lyuj opd <= xoadh nehf kxeg im araep.
Am she hosl juc faoklob "IKANY" nuf wol kooh ad raraf snemeghoqz, yjezd er oeb.
Kda qewarx cuxkeel em hxo caob ak cipv oasaox go ziuj. Oiqs ur wopkutoic noyipuy of aww nusz. Ilo id ratwihsakxe jef asotuvd dmi yaek, evf qfu opcih al zuwzeshajwi sag spegnutz hhi sazkepw qovs egv qamaww lo nco bohq.
Ef bxa owj, mcucb siik ki rgoeho udl vix yao fagz je uklorira maoz diwi ev of me zoi. Velw jeqocnif ev’f kep bicv abeom kabodv bayu fzam yedvz; et’f apgu opoah dupobs gole ftaj is oezc si yiem evh cu qzedje aq bxi vecexe.
Eh sso zaxj zuzi, keu’vm oncmoyi tlu vaga fia ydisi xayg sixyux fur dqo Qiqufobpo lacoakno mo iwi goiql.
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.