DEV Community

Davmi Jose Valdez Ogando
Davmi Jose Valdez Ogando

Posted on

100 Days of Swift - Day 4

Continuation of Hacking With Swift 100 Days of Swift

Day 4 - Looooooooops

  1. 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

  1. While loops
    Nothing fancy to see here

  2. Repeat Loops
    Basically do whiles

  3. Breaking and skipping in loops
    While the keyword continue 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.

Top comments (1)

davjvo profile image
Davmi Jose Valdez Ogando

PS: Search how do I format code with correct indentation later