This content originally appeared on DEV Community and was authored by Davmi Jose Valdez Ogando
Continuation of Hacking With Swift 100 Days of Swift
Day 4 - Looooooooops
- For loops
For loops are done on a python way (maybe swift did it first?) but without the required indentation. So if you want to loop through [1,2,3,4] you'd do:
for number in [1,2,3,4] { print(number) }
PS: Discard (the underscore _ ) is accepted if you don't want/need the actual variable
While loops
Nothing fancy to see hereRepeat Loops
Basically do whilesBreaking and skipping in loops
While the keywordcontinue
is just your everyday reserved word, breaks are really interesting.
Swift supports something called "labeled statements". Imagine the following nested loop:
for option1 in options {
for option2 in options {
// do code here
}
}
Like in other languages, if we use the keyword break
it will exit the inner loop only, inside a function we could add a return but that's if we are inside a function, so how do we exit the parent? well you give it a label and then you tell swift to break label_name;
example:
outerLoop: for option1 in options {
for option2 in options {
break outerLoop;
}
}
Pretty neat in my opinion.
This content originally appeared on DEV Community and was authored by Davmi Jose Valdez Ogando
Davmi Jose Valdez Ogando | Sciencx (2022-04-04T00:09:32+00:00) 100 Days of Swift – Day 4. Retrieved from https://www.scien.cx/2022/04/04/100-days-of-swift-day-4/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.